import omniORB
orb = omniORB.CORBA.ORB_init(sys.argv, omniORB.CORBA.ORB_ID)
import SALOME_NamingServicePy
- ns = SALOME_NamingServicePy.SALOME_NamingServicePy_i(orb)
+ ns = SALOME_NamingServicePy.SALOME_NamingServicePy_i(orb, 3, True)
import SALOME #@UnresolvedImport @UnusedImport
session = ns.Resolve("/Kernel/Session")
assert session
except:
+ killMyPort(port)
return
try:
status = session.GetStatSession()
server.CMD = [os.getenv("PYTHONBIN"), "-m", "killSalomeWithPort", "--spy", "%s"%(session_pid or os.getpid()), "%s"%(port)]
else:
server.CMD = ["killSalomeWithPort.py", "--spy", "%s"%(session_pid or os.getpid()), "%s"%(port)]
- server.run()
+ server.run(True)
# os.system("killSalomeWithPort.py --spy %s %s &"%(os.getpid(), port))
# --
dt = 1.0
test = test and args['foreground']
# --
if test:
+ from time import sleep
+ sleep(3.0)
foreGround(clt, args)
pass
pass
-# -*- coding: iso-8859-1 -*-
-# Copyright (C) 2007-2020 CEA/DEN, EDF R&D, OPEN CASCADE
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-
-# ---
-# File : salome_utils.py
-# Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com)
-# ---
-
-## @package salome_utils
-# \brief Set of utility functions used by SALOME python scripts.
-
-#
-# Exported functions
-#
-
-__all__ = [
- 'getORBcfgInfo',
- 'getHostFromORBcfg',
- 'getPortFromORBcfg',
- 'getUserName',
- 'getHostName',
- 'getShortHostName',
- 'getAppName',
- 'getPortNumber',
- 'getLogDir',
- 'getTmpDir',
- 'getHomeDir',
- 'generateFileName',
- 'makeTmpDir',
- 'uniteFiles',
- ]
-
-# ---
-
-def _try_bool( arg ):
- """
- Check if specified parameter represents boolean value and returns its value.
- String values like 'True', 'TRUE', 'YES', 'Yes', 'y', 'NO', 'false', 'n', etc
- are supported.
- If <arg> does not represent a boolean, an exception is raised.
- """
- if isinstance(arg, bool) :
- return arg
- elif isinstance(arg, (str, bytes)):
- v = str( arg ).lower()
- if v in [ "yes", "y", "true" ]: return True
- elif v in [ "no", "n", "false" ]: return False
- pass
- raise Exception("Not boolean value")
-
-# ---
-
-def getORBcfgInfo():
- """
- Get omniORB current configuration.
- Returns a list of three values: [ orb_version, host_name, port_number ].
-
- The information is retrieved from the omniORB configuration file defined
- by the OMNIORB_CONFIG environment variable.
- If omniORB configuration file can not be accessed, a list of three empty
- strings is returned.
- """
- import os, re
- ret = [ "", "", "" ]
- try:
- f = open( os.getenv( "OMNIORB_CONFIG" ) )
- lines = f.readlines()
- f.close()
- regvar = re.compile( "(ORB)?InitRef.*corbaname::(.*):(\d+)\s*$" )
- for l in lines:
- try:
- m = regvar.match( l )
- if m:
- if m.group(1) is None:
- ret[0] = "4"
- else:
- ret[0] = "3"
- pass
- ret[1] = m.group(2)
- ret[2] = m.group(3)
- break
- pass
- except:
- pass
- pass
- pass
- except:
- pass
- return ret
-
-# ---
-
-def getHostFromORBcfg():
- """
- Get current omniORB host.
- """
- return getORBcfgInfo()[1]
-# ---
-
-def getPortFromORBcfg():
- """
- Get current omniORB port.
- """
- return getORBcfgInfo()[2]
-
-# ---
-
-def getUserName():
- """
- Get user name:
- 1. try USER environment variable (USERNAME on windows)
- 2. if fails, try LOGNAME (un*x)
- 3. if fails return 'unknown' as default user name
- """
- import os, sys
- if sys.platform == "win32":
- return os.getenv("USERNAME", "unknown")
- else:
- user = os.getenv("USER")
- if user:
- return user
- return os.getenv("LOGNAME", "unknown")
-# ---
-
-def getHostName():
- """
- Get host name:
- 1. try socket python module gethostname() function
- 2. if fails, try HOSTNAME environment variable
- 3. if fails, try HOST environment variable
- 4. if fails, return 'unknown' as default host name
- """
- try:
- import socket
- host = socket.gethostname()
- except:
- host = None
- pass
- if not host: host = os.getenv("HOSTNAME")
- if not host: host = os.getenv("HOST")
- if not host: host = "unknown" # 'unknown' is default host name
- try:
- socket.gethostbyname(host)
- except:
- host = "localhost"
- pass
- return host
-
-# ---
-
-def getShortHostName():
- """
- Get short host name:
- 1. try socket python module gethostname() function
- 2. if fails, try HOSTNAME environment variable
- 3. if fails, try HOST environment variable
- 4. if fails, return 'unknown' as default host name
- """
- try:
- return getHostName().split('.')[0]
- except:
- pass
- return "unknown" # 'unknown' is default host name
-
-# ---
-
-def getAppName():
- """
- Get application name:
- 1. try APPNAME environment variable
- 2. if fails, return 'SALOME' as default application name
- """
- import os
- return os.getenv( "APPNAME", "SALOME" ) # 'SALOME' is default user name
-
-# ---
-
-def getPortNumber(use_default=True):
- """
- Get current naming server port number:
- 1. try NSPORT environment variable
- 1. if fails, try to parse config file defined by OMNIORB_CONFIG environment variable
- 2. if fails, return 2809 as default port number (if use_default is True) or None (id use_default is False)
- """
- import os
- try:
- return int( os.getenv( "NSPORT" ) )
- except:
- pass
- try:
- port = int( getPortFromORBcfg() )
- if port is not None: return port
- except:
- pass
- if use_default: return 2809 # '2809' is default port number
- return None
-
-# ---
-
-def getHomeDir():
- """
- Get home directory.
- """
- import os
- return os.path.realpath(os.path.expanduser('~'))
-# ---
-
-def getLogDir():
- """
- Get directory to be used for the log files.
- """
- import os
- return os.path.join(getTmpDir(), "logs", getUserName())
-# ---
-
-def getTmpDir():
- """
- Get directory to be used for the temporary files.
- """
- import os, tempfile
- f = tempfile.NamedTemporaryFile()
- tmpdir = os.path.dirname(f.name)
- f.close()
- return tmpdir
-# ---
-
-def generateFileName( dir, prefix = None, suffix = None, extension = None,
- unique = False, separator = "_", hidden = False, **kwargs ):
- """
- Generate file name by specified parameters. If necessary, file name
- can be generated to be unique.
-
- Parameters:
- - dir : directory path
- - prefix : file prefix (not added by default)
- - suffix : file suffix (not added by default)
- - extension : file extension (not added by default)
- - unique : if this parameter is True, the unique file name is generated:
- in this case, if the file with the generated name already exists
- in the <dir> directory, an integer suffix is added to the end of the
- file name. This parameter is False by default.
- - separator : separator of the words ('_' by default)
- - hidden : if this parameter is True, the file name is prepended by . (dot)
- symbol. This parameter is False by default.
-
- Other keyword parameters are:
- - with_username : 'add user name' flag/option:
- * boolean value can be passed to determine user name automatically
- * string value to be used as user name
- - with_hostname : 'add host name' flag/option:
- * boolean value can be passed to determine host name automatically
- * string value to be used as host name
- - with_port : 'add port number' flag/option:
- * boolean value can be passed to determine port number automatically
- * string value to be used as port number
- - with_app : 'add application name' flag/option:
- * boolean value can be passed to determine application name automatically
- * string value to be used as application name
- All <with_...> parameters are optional.
- """
- supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
- from launchConfigureParser import verbose
- filename = []
- # separator
- if separator is None:
- separator = ""
- pass
- else:
- separator = str( separator )
- pass
- # prefix (if specified)
- if prefix is not None:
- filename.append( str( prefix ) )
- pass
- # additional keywords
- ### check unsupported parameters
- for kw in kwargs:
- if kw not in supported and verbose():
- print('Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw)
- pass
- pass
- ### process supported keywords
- for kw in supported:
- if kw not in kwargs: continue
- ### user name
- if kw == 'with_username':
- try:
- # auto user name ?
- if _try_bool( kwargs[kw] ): filename.append( getUserName() )
- pass
- except:
- # user name given as parameter
- filename.append( kwargs[kw] )
- pass
- pass
- ### host name
- elif kw == 'with_hostname':
- try:
- # auto host name ?
- if _try_bool( kwargs[kw] ): filename.append( getShortHostName() )
- pass
- except:
- # host name given as parameter
- filename.append( kwargs[kw] )
- pass
- pass
- ### port number
- elif kw == 'with_port':
- try:
- # auto port number ?
- if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
- pass
- except:
- # port number given as parameter
- filename.append( str( kwargs[kw] ) )
- pass
- pass
- ### application name
- elif kw == 'with_app':
- try:
- # auto application name ?
- if _try_bool( kwargs[kw] ): filename.append( getAppName() )
- pass
- except:
- # application name given as parameter
- filename.append( kwargs[kw] )
- pass
- pass
- pass
- # suffix (if specified)
- if suffix is not None:
- filename.append( str( suffix ) )
- pass
- # raise an exception if file name is empty
- if not filename:
- raise Exception("Empty file name")
- #
- if extension is not None and extension.startswith("."): extension = extension[1:]
- #
- import os
- name = separator.join( filename )
- if hidden: name = "." + name # add dot for hidden files
- if extension: name = name + "." + str( extension ) # add extension if defined
- name = os.path.join( dir, name )
- if unique:
- # create unique file name
- index = 0
- while os.path.exists( name ):
- index = index + 1
- name = separator.join( filename ) + separator + str( index )
- if hidden: name = "." + name # add dot for hidden files
- if extension: name = name + "." + str( extension ) # add extension if defined
- name = os.path.join( dir, name )
- pass
- pass
- return os.path.normpath(name)
-
-# ---
-
-def makeTmpDir( path, mode=0o777 ):
- """
- Make temporary directory with the specified path.
- If the directory exists then clear its contents.
-
- Parameters:
- - path : absolute path to the directory to be created.
- - mode : access mode
- """
- import os
- if os.path.exists( path ):
- import sys
- if sys.platform == "win32":
- os.system( "rmdir /S /Q " + '"' + path + '"' )
- os.system( "mkdir " + '"' + path + '"' )
- else:
- os.system( "rm -rf " + path + "/*" )
- else:
- dirs = path.split("/")
- shift1 = shift2 = 0
- if not dirs[0]: shift1 = 1
- if dirs[-1]: shift2 = 1
- for i in range(1+shift1,len(dirs)+shift2):
- p = "/".join(dirs[:i])
- try:
- os.mkdir(p, mode)
- os.chmod(p, mode)
- except:
- pass
-
-# ---
-
-def uniteFiles( src_file, dest_file ):
- """
- Unite contents of the source file with contents of the destination file
- and put result of the uniting to the destination file.
- If the destination file does not exist then the source file is simply
- copied to its path.
-
- Parameters:
- - src_file : absolute path to the source file
- - dest_file : absolute path to the destination file
- """
- import os
-
- if not os.path.exists( src_file ):
- return
- pass
-
- if os.path.exists( dest_file ):
- # add a symbol of new line to contents of the destination file (just in case)
- dest = open( dest_file, 'r' )
- dest_lines = dest.readlines()
- dest.close()
-
- dest_lines.append( "\n" )
-
- dest = open( dest_file, 'w' )
- dest.writelines( dest_lines )
- dest.close()
-
- import sys
- if sys.platform == "win32":
- command = "type " + '"' + src_file + '"' + " >> " + '"' + dest_file + '"'
- else:
- command = "cat " + src_file + " >> " + dest_file
- pass
- pass
- else:
- import sys
- if sys.platform == "win32":
- command = "copy " + '"' + src_file + '"' + " " + '"' + dest_file + '"' + " > nul"
- else:
- command = "cp " + src_file + " " + dest_file
- pass
- pass
-
- os.system( command )
-
-# --
-
-_verbose = None
-
-def verbose():
- """
- Get verbosity level. Default verbosity level is specified via the environment variable
- SALOME_VERBOSE, e.g.:
- [bash %] export SALOME_VERBOSE=1
- The function setVerbose() can be used to change verbosity level explicitly.
- """
- global _verbose
- # verbose has already been called
- if _verbose is not None:
- return _verbose
- # first time
- try:
- from os import getenv
- _verbose = int(getenv('SALOME_VERBOSE'))
- except:
- _verbose = 0
- pass
- #
- return _verbose
-# --
-
-def setVerbose(level):
- """
- Change verbosity level. The function verbose() can be used to get current verbosity level.
- """
- global _verbose
- _verbose = level
- return
-# --
-
-import signal
-def killpid(pid, sig = 9):
- """
- Send signal sig to the process by pid.
-
- Parameters:
- - pid : PID of process
- - sig : signal for sending
- Possible values of signals:
- 9 means kill the process
- 0 only check existing of the process
- NOTE: Other values are not processed on Windows
- Returns:
- 1 Success
- 0 Fail, no such process
- -1 Fail, another reason
-
- """
- if not pid: return
- import os, sys
- if sig != 0:
- if verbose(): print("######## killpid pid = ", pid)
- try:
- if sys.platform == "win32":
- import ctypes
- if sig == 0:
- # PROCESS_QUERY_INFORMATION (0x0400) Required to retrieve certain information about a process
- handle = ctypes.windll.kernel32.OpenProcess(0x0400, False, int(pid))
- if handle:
- ret = 1
- ctypes.windll.kernel32.CloseHandle(handle)
- else:
- ret = 0
- if sig == 9:
- # PROCESS_TERMINATE (0x0001) Required to terminate a process using TerminateProcess.
- handle = ctypes.windll.kernel32.OpenProcess(0x0001, False, int(pid))
- ret = ctypes.windll.kernel32.TerminateProcess(handle, -1)
- ctypes.windll.kernel32.CloseHandle(handle)
- pass
- pass
- else:
- # Default: signal.SIGKILL = 9
- os.kill(int(pid),sig)
- ret = 1
- pass
- pass
- except OSError as e:
- # errno.ESRCH == 3 is 'No such process'
- if e.errno == 3:
- ret = 0
- else:
- ret = -1
- pass
- pass
- return ret
-# --
-
-def getOmniNamesPid(port):
- """
- Return OmniNames pid by port number.
- """
- import sys,subprocess,re
- if sys.platform == "win32":
- # Get process list by WMI Command Line Utility(WMIC)
- # Output is formatted with each value listed on a separate line and with the name of the property:
- # ...
- # Caption=<caption0>
- # CommandLine=<commandline0>
- # ProcessId=<processid0>
- #
- #
- #
- # Caption=<caption1>
- # CommandLine=<commandline1>
- # ProcessId=<processid1>
- # ...
- cmd = 'WMIC PROCESS get Caption,Commandline,Processid /VALUE'
- proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
- # Get stdout
- allProc = proc.communicate()[0].decode()
- # find Pid of omniNames
- pid = re.findall(r'Caption=.*omniNames.*\n?CommandLine=.*omniNames.*\D%s\D.*\n?ProcessId=(\d*)'%(port),allProc)[0]
- else:
- cmd = "ps -eo pid,command | grep -v grep | grep -E \"omniNames.*%s\" | awk '{print $1}'"%(port)
- proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
- pid = proc.communicate()[0]
- pass
-
- return pid
-# --
-
-def killOmniNames(port):
- """
- Kill OmniNames process by port number.
- """
- try:
- pid = getOmniNamesPid(port)
- if pid: killpid(pid)
- except:
- pass
- pass
-# --
+# -*- coding: iso-8859-1 -*-\r
+# Copyright (C) 2007-2020 CEA/DEN, EDF R&D, OPEN CASCADE\r
+#\r
+# This library is free software; you can redistribute it and/or\r
+# modify it under the terms of the GNU Lesser General Public\r
+# License as published by the Free Software Foundation; either\r
+# version 2.1 of the License, or (at your option) any later version.\r
+#\r
+# This library is distributed in the hope that it will be useful,\r
+# but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r
+# Lesser General Public License for more details.\r
+#\r
+# You should have received a copy of the GNU Lesser General Public\r
+# License along with this library; if not, write to the Free Software\r
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+#\r
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com\r
+#\r
+\r
+# ---\r
+# File : salome_utils.py\r
+# Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com)\r
+# ---\r
+\r
+## @package salome_utils\r
+# \brief Set of utility functions used by SALOME python scripts.\r
+\r
+#\r
+# Exported functions\r
+#\r
+\r
+__all__ = [\r
+ 'getORBcfgInfo',\r
+ 'getHostFromORBcfg',\r
+ 'getPortFromORBcfg',\r
+ 'getUserName',\r
+ 'getHostName',\r
+ 'getShortHostName',\r
+ 'getAppName',\r
+ 'getPortNumber',\r
+ 'getLogDir',\r
+ 'getTmpDir',\r
+ 'getHomeDir',\r
+ 'generateFileName',\r
+ 'makeTmpDir',\r
+ 'uniteFiles',\r
+ ]\r
+\r
+# ---\r
+\r
+def _try_bool( arg ):\r
+ """\r
+ Check if specified parameter represents boolean value and returns its value.\r
+ String values like 'True', 'TRUE', 'YES', 'Yes', 'y', 'NO', 'false', 'n', etc\r
+ are supported.\r
+ If <arg> does not represent a boolean, an exception is raised.\r
+ """\r
+ if isinstance(arg, bool) :\r
+ return arg\r
+ elif isinstance(arg, (str, bytes)):\r
+ v = str( arg ).lower()\r
+ if v in [ "yes", "y", "true" ]: return True\r
+ elif v in [ "no", "n", "false" ]: return False\r
+ pass\r
+ raise Exception("Not boolean value")\r
+\r
+# ---\r
+\r
+def getORBcfgInfo():\r
+ """\r
+ Get omniORB current configuration.\r
+ Returns a list of three values: [ orb_version, host_name, port_number ].\r
+\r
+ The information is retrieved from the omniORB configuration file defined\r
+ by the OMNIORB_CONFIG environment variable.\r
+ If omniORB configuration file can not be accessed, a list of three empty\r
+ strings is returned.\r
+ """\r
+ import os, re\r
+ ret = [ "", "", "" ]\r
+ try:\r
+ f = open( os.getenv( "OMNIORB_CONFIG" ) )\r
+ lines = f.readlines()\r
+ f.close()\r
+ regvar = re.compile( "(ORB)?InitRef.*corbaname::(.*):(\d+)\s*$" )\r
+ for l in lines:\r
+ try:\r
+ m = regvar.match( l )\r
+ if m:\r
+ if m.group(1) is None:\r
+ ret[0] = "4"\r
+ else:\r
+ ret[0] = "3"\r
+ pass\r
+ ret[1] = m.group(2)\r
+ ret[2] = m.group(3)\r
+ break\r
+ pass\r
+ except:\r
+ pass\r
+ pass\r
+ pass\r
+ except:\r
+ pass\r
+ return ret\r
+\r
+# ---\r
+\r
+def getHostFromORBcfg():\r
+ """\r
+ Get current omniORB host.\r
+ """\r
+ return getORBcfgInfo()[1]\r
+# ---\r
+\r
+def getPortFromORBcfg():\r
+ """\r
+ Get current omniORB port.\r
+ """\r
+ return getORBcfgInfo()[2]\r
+\r
+# ---\r
+\r
+def getUserName():\r
+ """\r
+ Get user name:\r
+ 1. try USER environment variable (USERNAME on windows)\r
+ 2. if fails, try LOGNAME (un*x)\r
+ 3. if fails return 'unknown' as default user name\r
+ """\r
+ import os, sys\r
+ if sys.platform == "win32":\r
+ return os.getenv("USERNAME", "unknown")\r
+ else:\r
+ user = os.getenv("USER")\r
+ if user:\r
+ return user\r
+ return os.getenv("LOGNAME", "unknown")\r
+# ---\r
+\r
+def getHostName():\r
+ """\r
+ Get host name:\r
+ 1. try socket python module gethostname() function\r
+ 2. if fails, try HOSTNAME environment variable\r
+ 3. if fails, try HOST environment variable\r
+ 4. if fails, return 'unknown' as default host name\r
+ """\r
+ try:\r
+ import socket\r
+ host = socket.gethostname()\r
+ except:\r
+ host = None\r
+ pass\r
+ if not host: host = os.getenv("HOSTNAME")\r
+ if not host: host = os.getenv("HOST")\r
+ if not host: host = "unknown" # 'unknown' is default host name\r
+ try:\r
+ socket.gethostbyname(host)\r
+ except:\r
+ host = "localhost"\r
+ pass\r
+ return host\r
+\r
+# ---\r
+\r
+def getShortHostName():\r
+ """\r
+ Get short host name:\r
+ 1. try socket python module gethostname() function\r
+ 2. if fails, try HOSTNAME environment variable\r
+ 3. if fails, try HOST environment variable\r
+ 4. if fails, return 'unknown' as default host name\r
+ """\r
+ try:\r
+ return getHostName().split('.')[0]\r
+ except:\r
+ pass\r
+ return "unknown" # 'unknown' is default host name\r
+\r
+# ---\r
+\r
+def getAppName():\r
+ """\r
+ Get application name:\r
+ 1. try APPNAME environment variable\r
+ 2. if fails, return 'SALOME' as default application name\r
+ """\r
+ import os\r
+ return os.getenv( "APPNAME", "SALOME" ) # 'SALOME' is default user name\r
+\r
+# ---\r
+\r
+def getPortNumber(use_default=True):\r
+ """\r
+ Get current naming server port number:\r
+ 1. try NSPORT environment variable\r
+ 1. if fails, try to parse config file defined by OMNIORB_CONFIG environment variable\r
+ 2. if fails, return 2809 as default port number (if use_default is True) or None (id use_default is False)\r
+ """\r
+ import os\r
+ try:\r
+ return int( os.getenv( "NSPORT" ) )\r
+ except:\r
+ pass\r
+ try:\r
+ port = int( getPortFromORBcfg() )\r
+ if port is not None: return port\r
+ except:\r
+ pass\r
+ if use_default: return 2809 # '2809' is default port number\r
+ return None\r
+\r
+# ---\r
+\r
+def getHomeDir():\r
+ """\r
+ Get home directory.\r
+ """\r
+ import os\r
+ return os.path.realpath(os.path.expanduser('~'))\r
+# ---\r
+\r
+def getLogDir():\r
+ """\r
+ Get directory to be used for the log files.\r
+ """\r
+ import os\r
+ return os.path.join(getTmpDir(), "logs", getUserName())\r
+# ---\r
+\r
+def getTmpDir():\r
+ """\r
+ Get directory to be used for the temporary files.\r
+ """\r
+ import os, tempfile\r
+ f = tempfile.NamedTemporaryFile()\r
+ tmpdir = os.path.dirname(f.name)\r
+ f.close()\r
+ return tmpdir\r
+# ---\r
+\r
+def generateFileName( dir, prefix = None, suffix = None, extension = None,\r
+ unique = False, separator = "_", hidden = False, **kwargs ):\r
+ """\r
+ Generate file name by specified parameters. If necessary, file name\r
+ can be generated to be unique.\r
+\r
+ Parameters:\r
+ - dir : directory path\r
+ - prefix : file prefix (not added by default)\r
+ - suffix : file suffix (not added by default)\r
+ - extension : file extension (not added by default)\r
+ - unique : if this parameter is True, the unique file name is generated:\r
+ in this case, if the file with the generated name already exists\r
+ in the <dir> directory, an integer suffix is added to the end of the\r
+ file name. This parameter is False by default.\r
+ - separator : separator of the words ('_' by default)\r
+ - hidden : if this parameter is True, the file name is prepended by . (dot)\r
+ symbol. This parameter is False by default.\r
+\r
+ Other keyword parameters are:\r
+ - with_username : 'add user name' flag/option:\r
+ * boolean value can be passed to determine user name automatically\r
+ * string value to be used as user name\r
+ - with_hostname : 'add host name' flag/option:\r
+ * boolean value can be passed to determine host name automatically\r
+ * string value to be used as host name\r
+ - with_port : 'add port number' flag/option:\r
+ * boolean value can be passed to determine port number automatically\r
+ * string value to be used as port number\r
+ - with_app : 'add application name' flag/option:\r
+ * boolean value can be passed to determine application name automatically\r
+ * string value to be used as application name\r
+ All <with_...> parameters are optional.\r
+ """\r
+ supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]\r
+ from launchConfigureParser import verbose\r
+ filename = []\r
+ # separator\r
+ if separator is None:\r
+ separator = ""\r
+ pass\r
+ else:\r
+ separator = str( separator )\r
+ pass\r
+ # prefix (if specified)\r
+ if prefix is not None:\r
+ filename.append( str( prefix ) )\r
+ pass\r
+ # additional keywords\r
+ ### check unsupported parameters\r
+ for kw in kwargs:\r
+ if kw not in supported and verbose():\r
+ print('Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw)\r
+ pass\r
+ pass\r
+ ### process supported keywords\r
+ for kw in supported:\r
+ if kw not in kwargs: continue\r
+ ### user name\r
+ if kw == 'with_username':\r
+ try:\r
+ # auto user name ?\r
+ if _try_bool( kwargs[kw] ): filename.append( getUserName() )\r
+ pass\r
+ except:\r
+ # user name given as parameter\r
+ filename.append( kwargs[kw] )\r
+ pass\r
+ pass\r
+ ### host name\r
+ elif kw == 'with_hostname':\r
+ try:\r
+ # auto host name ?\r
+ if _try_bool( kwargs[kw] ): filename.append( getShortHostName() )\r
+ pass\r
+ except:\r
+ # host name given as parameter\r
+ filename.append( kwargs[kw] )\r
+ pass\r
+ pass\r
+ ### port number\r
+ elif kw == 'with_port':\r
+ try:\r
+ # auto port number ?\r
+ if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )\r
+ pass\r
+ except:\r
+ # port number given as parameter\r
+ filename.append( str( kwargs[kw] ) )\r
+ pass\r
+ pass\r
+ ### application name\r
+ elif kw == 'with_app':\r
+ try:\r
+ # auto application name ?\r
+ if _try_bool( kwargs[kw] ): filename.append( getAppName() )\r
+ pass\r
+ except:\r
+ # application name given as parameter\r
+ filename.append( kwargs[kw] )\r
+ pass\r
+ pass\r
+ pass\r
+ # suffix (if specified)\r
+ if suffix is not None:\r
+ filename.append( str( suffix ) )\r
+ pass\r
+ # raise an exception if file name is empty\r
+ if not filename:\r
+ raise Exception("Empty file name")\r
+ #\r
+ if extension is not None and extension.startswith("."): extension = extension[1:]\r
+ #\r
+ import os\r
+ name = separator.join( filename )\r
+ if hidden: name = "." + name # add dot for hidden files\r
+ if extension: name = name + "." + str( extension ) # add extension if defined\r
+ name = os.path.join( dir, name )\r
+ if unique:\r
+ # create unique file name\r
+ index = 0\r
+ while os.path.exists( name ):\r
+ index = index + 1\r
+ name = separator.join( filename ) + separator + str( index )\r
+ if hidden: name = "." + name # add dot for hidden files\r
+ if extension: name = name + "." + str( extension ) # add extension if defined\r
+ name = os.path.join( dir, name )\r
+ pass\r
+ pass\r
+ return os.path.normpath(name)\r
+\r
+# ---\r
+\r
+def makeTmpDir( path, mode=0o777 ):\r
+ """\r
+ Make temporary directory with the specified path.\r
+ If the directory exists then clear its contents.\r
+\r
+ Parameters:\r
+ - path : absolute path to the directory to be created.\r
+ - mode : access mode\r
+ """\r
+ import os\r
+ if os.path.exists( path ):\r
+ import sys\r
+ if sys.platform == "win32":\r
+ os.system( "rmdir /S /Q " + '"' + path + '"' )\r
+ os.system( "mkdir " + '"' + path + '"' )\r
+ else:\r
+ os.system( "rm -rf " + path + "/*" )\r
+ else:\r
+ dirs = path.split("/")\r
+ shift1 = shift2 = 0\r
+ if not dirs[0]: shift1 = 1\r
+ if dirs[-1]: shift2 = 1\r
+ for i in range(1+shift1,len(dirs)+shift2):\r
+ p = "/".join(dirs[:i])\r
+ try:\r
+ os.mkdir(p, mode)\r
+ os.chmod(p, mode)\r
+ except:\r
+ pass\r
+\r
+# ---\r
+\r
+def uniteFiles( src_file, dest_file ):\r
+ """\r
+ Unite contents of the source file with contents of the destination file\r
+ and put result of the uniting to the destination file.\r
+ If the destination file does not exist then the source file is simply\r
+ copied to its path.\r
+\r
+ Parameters:\r
+ - src_file : absolute path to the source file\r
+ - dest_file : absolute path to the destination file\r
+ """\r
+ import os\r
+\r
+ if not os.path.exists( src_file ):\r
+ return\r
+ pass\r
+\r
+ if os.path.exists( dest_file ):\r
+ # add a symbol of new line to contents of the destination file (just in case)\r
+ dest = open( dest_file, 'r' )\r
+ dest_lines = dest.readlines()\r
+ dest.close()\r
+\r
+ dest_lines.append( "\n" )\r
+\r
+ dest = open( dest_file, 'w' )\r
+ dest.writelines( dest_lines )\r
+ dest.close()\r
+\r
+ import sys\r
+ if sys.platform == "win32":\r
+ command = "type " + '"' + src_file + '"' + " >> " + '"' + dest_file + '"'\r
+ else:\r
+ command = "cat " + src_file + " >> " + dest_file\r
+ pass\r
+ pass\r
+ else:\r
+ import sys\r
+ if sys.platform == "win32":\r
+ command = "copy " + '"' + src_file + '"' + " " + '"' + dest_file + '"' + " > nul"\r
+ else:\r
+ command = "cp " + src_file + " " + dest_file\r
+ pass\r
+ pass\r
+\r
+ os.system( command )\r
+\r
+# --\r
+\r
+_verbose = None\r
+\r
+def verbose():\r
+ """\r
+ Get verbosity level. Default verbosity level is specified via the environment variable\r
+ SALOME_VERBOSE, e.g.:\r
+ [bash %] export SALOME_VERBOSE=1\r
+ The function setVerbose() can be used to change verbosity level explicitly.\r
+ """\r
+ global _verbose\r
+ # verbose has already been called\r
+ if _verbose is not None:\r
+ return _verbose\r
+ # first time\r
+ try:\r
+ from os import getenv\r
+ _verbose = int(getenv('SALOME_VERBOSE'))\r
+ except:\r
+ _verbose = 0\r
+ pass\r
+ #\r
+ return _verbose\r
+# --\r
+\r
+def setVerbose(level):\r
+ """\r
+ Change verbosity level. The function verbose() can be used to get current verbosity level.\r
+ """\r
+ global _verbose\r
+ _verbose = level\r
+ return\r
+# --\r
+\r
+import signal\r
+def killpid(pid, sig = 9):\r
+ """\r
+ Send signal sig to the process by pid.\r
+\r
+ Parameters:\r
+ - pid : PID of process\r
+ - sig : signal for sending\r
+ Possible values of signals: \r
+ 9 means kill the process\r
+ 0 only check existing of the process\r
+ NOTE: Other values are not processed on Windows\r
+ Returns:\r
+ 1 Success\r
+ 0 Fail, no such process\r
+ -1 Fail, another reason\r
+\r
+ """\r
+ if not pid: return\r
+ import os, sys\r
+ if sig != 0:\r
+ if verbose(): print("######## killpid pid = ", pid)\r
+ try:\r
+ if sys.platform == "win32":\r
+ import ctypes\r
+ if sig == 0:\r
+ # PROCESS_QUERY_INFORMATION (0x0400) Required to retrieve certain information about a process\r
+ SYNCHRONIZE = 0x100000\r
+ handle = ctypes.windll.kernel32.OpenProcess(SYNCHRONIZE, False, int(pid))\r
+ waitObj = ctypes.windll.kernel32.WaitForSingleObject(handle, 0)\r
+ if waitObj:\r
+ ret = 1\r
+ ctypes.windll.kernel32.CloseHandle(handle)\r
+ else:\r
+ ret = 0\r
+ if sig == 9:\r
+ # PROCESS_TERMINATE (0x0001) Required to terminate a process using TerminateProcess.\r
+ handle = ctypes.windll.kernel32.OpenProcess(0x0001, False, int(pid))\r
+ ret = ctypes.windll.kernel32.TerminateProcess(handle, -1)\r
+ ctypes.windll.kernel32.CloseHandle(handle)\r
+ pass\r
+ pass\r
+ else:\r
+ # Default: signal.SIGKILL = 9\r
+ os.kill(int(pid),sig)\r
+ ret = 1\r
+ pass\r
+ pass\r
+ except OSError as e:\r
+ # errno.ESRCH == 3 is 'No such process'\r
+ if e.errno == 3:\r
+ ret = 0\r
+ else:\r
+ ret = -1\r
+ pass\r
+ pass\r
+ return ret\r
+# --\r
+\r
+def getOmniNamesPid(port):\r
+ """\r
+ Return OmniNames pid by port number.\r
+ """\r
+ import sys,subprocess,re\r
+ if sys.platform == "win32":\r
+ # Get process list by WMI Command Line Utility(WMIC)\r
+ # Output is formatted with each value listed on a separate line and with the name of the property:\r
+ # ...\r
+ # Caption=<caption0>\r
+ # CommandLine=<commandline0>\r
+ # ProcessId=<processid0>\r
+ #\r
+ #\r
+ #\r
+ # Caption=<caption1>\r
+ # CommandLine=<commandline1>\r
+ # ProcessId=<processid1>\r
+ # ...\r
+ cmd = 'WMIC PROCESS get Caption,Commandline,Processid /VALUE'\r
+ proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\r
+ # Get stdout\r
+ allProc = proc.communicate()[0].decode()\r
+ # find Pid of omniNames\r
+ pid = re.findall(r'Caption=.*omniNames.*\n?CommandLine=.*omniNames.*\D%s\D.*\n?ProcessId=(\d*)'%(port),allProc)[0]\r
+ else: \r
+ cmd = "ps -eo pid,command | grep -v grep | grep -E \"omniNames.*%s\" | awk '{print $1}'"%(port)\r
+ proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\r
+ pid = proc.communicate()[0]\r
+ pass\r
+\r
+ return pid\r
+# --\r
+\r
+def killOmniNames(port):\r
+ """\r
+ Kill OmniNames process by port number.\r
+ """\r
+ try:\r
+ pid = getOmniNamesPid(port)\r
+ if pid: killpid(pid)\r
+ except:\r
+ pass\r
+ pass\r
+# --\r
-# -*- coding: iso-8859-1 -*-
-# Copyright (C) 2007-2020 CEA/DEN, EDF R&D, OPEN CASCADE
-#
-# Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-# CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-
-import os, sys, string
-from salome_utils import getHostName
-process_id = {}
-
-# -----------------------------------------------------------------------------
-#
-# Definition des classes d'objets pour le lancement des Server CORBA
-#
-
-class Server:
- """Generic class for CORBA server launch"""
-
- server_launch_mode = "daemon"
-
- def initArgs(self):
- self.PID=None
- self.CMD=[]
- self.ARGS=[]
- if self.args.get('xterm'):
- if sys.platform != "win32":
- self.ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-hold']
- else:
- self.ARGS=['cmd', '/c', 'start cmd.exe', '/K']
-
- def __init__(self,args):
- self.args=args
- self.initArgs()
-
- @staticmethod
- def set_server_launch_mode(mode):
- if mode == "daemon" or mode == "fork":
- Server.server_launch_mode = mode
- else:
- raise Exception("Unsupported server launch mode: %s" % mode)
-
- def run(self):
- global process_id
- myargs=self.ARGS
- if self.args.get('xterm'):
- # (Debian) send LD_LIBRARY_PATH to children shells (xterm)
- if sys.platform == "darwin":
- env_ld_library_path=['env', 'DYLD_LIBRARY_PATH='
- + os.getenv("DYLD_FALLBACK_LIBRARY_PATH")]
- myargs = myargs +['-T']+self.CMD[:1]+['-e'] + env_ld_library_path
- elif sys.platform != "win32":
- env_ld_library_path=['env', 'LD_LIBRARY_PATH='
- + os.getenv("LD_LIBRARY_PATH")]
- myargs = myargs +['-T']+self.CMD[:1]+['-e'] + env_ld_library_path
- command = myargs + self.CMD
- # print("command = ", command)
- if sys.platform == "win32":
- import subprocess
- pid = subprocess.Popen(command).pid
- elif Server.server_launch_mode == "fork":
- pid = os.spawnvp(os.P_NOWAIT, command[0], command)
- else: # Server launch mode is daemon
- pid=self.daemonize(command)
- if pid is not None:
- #store process pid if it really exists
- process_id[pid]=self.CMD
- self.PID = pid
- return pid
-
- def daemonize(self,args):
- # to daemonize a process need to do the UNIX double-fork magic
- # see Stevens, "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177)
- # and UNIX Programming FAQ 1.7 How do I get my program to act like a daemon?
- # http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
- #open a pipe
- c2pread, c2pwrite = os.pipe()
- #do first fork
- pid=os.fork()
- if pid > 0:
- #first parent
- os.close(c2pwrite)
- #receive real pid from child
- data=os.read(c2pread,24) #read 24 bytes
- os.waitpid(pid,0) #remove zombie
- os.close(c2pread)
- # return : first parent
- childpid=int(data)
- if childpid==-1:
- return None
- try:
- os.kill(childpid,0)
- return childpid
- except:
- return None
-
- #first child
- # decouple from parent environment
- os.setsid()
- os.close(c2pread)
-
- # do second fork : second child not a session leader
- try:
- pid = os.fork()
- if pid > 0:
- #send real pid to parent
- pid_str = "%d" % pid
- os.write(c2pwrite,pid_str.encode())
- os.close(c2pwrite)
- # exit from second parent
- os._exit(0)
- except OSError as e:
- print("fork #2 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr)
- os.write(c2pwrite,"-1")
- os.close(c2pwrite)
- sys.exit(1)
-
- #I am a daemon
- os.close(0) #close stdin
- os.open("/dev/null", os.O_RDWR) # redirect standard input (0) to /dev/null
- try:
- os.execvp(args[0], args)
- except OSError as e:
- print("(%s) launch failed: %d (%s)" % (args[0],e.errno, e.strerror), file=sys.stderr)
- os._exit(127)
+# -*- coding: iso-8859-1 -*-\r
+# Copyright (C) 2007-2020 CEA/DEN, EDF R&D, OPEN CASCADE\r
+#\r
+# Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,\r
+# CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS\r
+#\r
+# This library is free software; you can redistribute it and/or\r
+# modify it under the terms of the GNU Lesser General Public\r
+# License as published by the Free Software Foundation; either\r
+# version 2.1 of the License, or (at your option) any later version.\r
+#\r
+# This library is distributed in the hope that it will be useful,\r
+# but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r
+# Lesser General Public License for more details.\r
+#\r
+# You should have received a copy of the GNU Lesser General Public\r
+# License along with this library; if not, write to the Free Software\r
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+#\r
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com\r
+#\r
+\r
+import os, sys, string\r
+from salome_utils import getHostName\r
+process_id = {}\r
+\r
+# -----------------------------------------------------------------------------\r
+#\r
+# Definition des classes d'objets pour le lancement des Server CORBA\r
+#\r
+\r
+class Server:\r
+ """Generic class for CORBA server launch"""\r
+\r
+ server_launch_mode = "daemon"\r
+\r
+ def initArgs(self):\r
+ self.PID=None\r
+ self.CMD=[]\r
+ self.ARGS=[]\r
+ if self.args.get('xterm'):\r
+ if sys.platform != "win32":\r
+ self.ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-hold']\r
+ else:\r
+ self.ARGS=['cmd', '/c', 'start cmd.exe', '/K']\r
+\r
+ def __init__(self,args):\r
+ self.args=args\r
+ self.initArgs()\r
+\r
+ @staticmethod\r
+ def set_server_launch_mode(mode):\r
+ if mode == "daemon" or mode == "fork":\r
+ Server.server_launch_mode = mode\r
+ else:\r
+ raise Exception("Unsupported server launch mode: %s" % mode)\r
+\r
+ def run(self, daemon=False):\r
+ global process_id\r
+ myargs=self.ARGS\r
+ if self.args.get('xterm'):\r
+ # (Debian) send LD_LIBRARY_PATH to children shells (xterm)\r
+ if sys.platform == "darwin":\r
+ env_ld_library_path=['env', 'DYLD_LIBRARY_PATH='\r
+ + os.getenv("DYLD_FALLBACK_LIBRARY_PATH")]\r
+ myargs = myargs +['-T']+self.CMD[:1]+['-e'] + env_ld_library_path\r
+ elif sys.platform != "win32":\r
+ env_ld_library_path=['env', 'LD_LIBRARY_PATH='\r
+ + os.getenv("LD_LIBRARY_PATH")]\r
+ myargs = myargs +['-T']+self.CMD[:1]+['-e'] + env_ld_library_path\r
+ command = myargs + self.CMD\r
+ # print("command = ", command)\r
+ if sys.platform == "win32":\r
+ import subprocess\r
+ if daemon:\r
+ DETACHED_PROCESS = 0x00000008\r
+ pid = subprocess.Popen(command, creationflags=DETACHED_PROCESS).pid\r
+ else:\r
+ pid = subprocess.Popen(command).pid\r
+ elif Server.server_launch_mode == "fork":\r
+ pid = os.spawnvp(os.P_NOWAIT, command[0], command)\r
+ else: # Server launch mode is daemon\r
+ pid=self.daemonize(command)\r
+ if pid is not None:\r
+ #store process pid if it really exists\r
+ process_id[pid]=self.CMD\r
+ self.PID = pid\r
+ return pid\r
+\r
+ def daemonize(self,args):\r
+ # to daemonize a process need to do the UNIX double-fork magic\r
+ # see Stevens, "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177)\r
+ # and UNIX Programming FAQ 1.7 How do I get my program to act like a daemon?\r
+ # http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16\r
+ #open a pipe\r
+ c2pread, c2pwrite = os.pipe()\r
+ #do first fork\r
+ pid=os.fork()\r
+ if pid > 0:\r
+ #first parent\r
+ os.close(c2pwrite)\r
+ #receive real pid from child\r
+ data=os.read(c2pread,24) #read 24 bytes\r
+ os.waitpid(pid,0) #remove zombie\r
+ os.close(c2pread)\r
+ # return : first parent\r
+ childpid=int(data)\r
+ if childpid==-1:\r
+ return None\r
+ try:\r
+ os.kill(childpid,0)\r
+ return childpid\r
+ except:\r
+ return None\r
+\r
+ #first child\r
+ # decouple from parent environment\r
+ os.setsid()\r
+ os.close(c2pread)\r
+\r
+ # do second fork : second child not a session leader\r
+ try:\r
+ pid = os.fork()\r
+ if pid > 0:\r
+ #send real pid to parent\r
+ pid_str = "%d" % pid\r
+ os.write(c2pwrite,pid_str.encode())\r
+ os.close(c2pwrite)\r
+ # exit from second parent\r
+ os._exit(0)\r
+ except OSError as e:\r
+ print("fork #2 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr)\r
+ os.write(c2pwrite,"-1")\r
+ os.close(c2pwrite)\r
+ sys.exit(1)\r
+\r
+ #I am a daemon\r
+ os.close(0) #close stdin\r
+ os.open("/dev/null", os.O_RDWR) # redirect standard input (0) to /dev/null\r
+ try:\r
+ os.execvp(args[0], args)\r
+ except OSError as e:\r
+ print("(%s) launch failed: %d (%s)" % (args[0],e.errno, e.strerror), file=sys.stderr)\r
+ os._exit(127)\r
-#! /usr/bin/env python3
-# -*- coding: iso-8859-1 -*-
-# Copyright (C) 2007-2020 CEA/DEN, EDF R&D, OPEN CASCADE
-#
-# Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-# CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-
-# SALOME NamingService : wrapping NamingService services
-# File : SALOME_NamingServicePy.py
-# Author : Estelle Deville, CEA
-# Module : SALOME
-# $Header$
-## @package SALOME_NamingServicePy
-# \brief Module to manage SALOME naming service from python
-#
-import sys
-import time
-from omniORB import CORBA
-import CosNaming
-import string
-from string import *
-
-from SALOME_utilities import *
-#=============================================================================
-
-class SALOME_NamingServicePy_i(object):
- """
- A class to manage SALOME naming service from python code
- """
- _orb = None
- _root_context=None
- _current_context=None
- _obj=None
-
- #-------------------------------------------------------------------------
-
- def __init__(self, orb=None):
- """
- Standard Constructor, with ORB reference.
-
- Initializes the naming service root context
- """
- #MESSAGE ( "SALOME_NamingServicePy_i::__init__" )
- if orb is None:
- orb=CORBA.ORB_init([''], CORBA.ORB_ID)
- self._orb = orb
- # initialize root context and current context
- ok = 0
- steps = 240
- while steps > 0 and ok == 0:
- try:
- obj =self._orb.resolve_initial_references("NameService")
- self._root_context =obj._narrow(CosNaming.NamingContext)
- self._current_context = self._root_context
-
-
- if self._root_context is None :
- #MESSAGE ( "Name Service Reference is invalid" )
- #sys.exit(1)
- MESSAGE(" Name service not found")
- else:
- ok = 1
- except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
- MESSAGE(" Name service not found")
- time.sleep(0.25)
- steps = steps - 1
- if steps == 0 and self._root_context is None:
- MESSAGE ( "Name Service Reference is invalid" )
- sys.exit(1)
-
- #-------------------------------------------------------------------------
-
- def Register(self,ObjRef, Path):
- """ ns.Register(object,pathname )
-
- register a CORBA object under a pathname
- """
-
- MESSAGE ( "SALOME_NamingServicePy_i::Register" )
- _not_exist = 0
- path_list = list(Path)
- if path_list[0]=='/':
- self._current_context = self._root_context
- #delete first '/' before split
- Path=Path[1:]
-
- result_resolve_path = Path.split('/')
- if len(result_resolve_path)>1:
- # A directory is treated (not only an object name)
- # We had to test if the directory where ObjRef should be recorded
- # is already done
- # If not, the new context has to be created
- _context_name = []
- for i in range(len(result_resolve_path)-1):
- _context_name.append(CosNaming.NameComponent(result_resolve_path[i],"dir"))
-
- try:
- obj = self._current_context.resolve(_context_name)
- self._current_context = obj._narrow(CosNaming.NamingContext)
- except CosNaming.NamingContext.NotFound as ex:
- _not_exist = 1
- except CosNaming.NamingContext.InvalidName as ex:
- MESSAGE ( "Register : CosNaming.NamingContext.InvalidName" )
- except CosNaming.NamingContext.CannotProceed as ex:
- MESSAGE ( "Register : CosNaming.NamingContext.CannotProceed" )
- except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
- MESSAGE ( "Register : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" )
-
- if _not_exist:
- # at least one context of the complete path is not created, we had
- # to create it or them
- _context_name = []
- for i in range(len(result_resolve_path)-1):
- _context_name = [CosNaming.NameComponent(result_resolve_path[i],"dir")]
-
- try:
- obj = self._current_context.resolve(_context_name)
- self._current_context = obj._narrow(CosNaming.NamingContext)
- except CosNaming.NamingContext.NotFound as ex:
- #This context is not created. It will be done
- self._current_context = self._current_context.bind_new_context(_context_name)
-
- #The current directory is now the directory where the object should
- #be recorded
-
- _context_name = [CosNaming.NameComponent(result_resolve_path[len(result_resolve_path)-1],"object")]
- try:
- self._current_context.bind(_context_name,ObjRef)
- except CosNaming.NamingContext.NotFound as ex:
- MESSAGE ( "Register : CosNaming.NamingContext.NotFound" )
- except CosNaming.NamingContext.InvalidName as ex:
- MESSAGE ( "Register : CosNaming.NamingContext.InvalidName" )
- except CosNaming.NamingContext.CannotProceed as ex:
- MESSAGE ( "Register : CosNaming.NamingContext.CannotProceed" )
- except CosNaming.NamingContext.AlreadyBound as ex:
- MESSAGE ( "Register : CosNaming.NamingContext.AlreadyBound, object will be rebind" )
- self._current_context.rebind(_context_name,ObjRef)
- except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
- MESSAGE ( "Register : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" )
-
- #-------------------------------------------------------------------------
-
- def Resolve(self, Path):
- """ ns.Resolve(pathname) -> object
-
- find a CORBA object (ior) by its pathname
- """
- #MESSAGE ( "SALOME_NamingServicePy_i::Resolve" )
- path_list = list(Path)
- if path_list[0]=='/':
- self._current_context = self._root_context
- #delete first '/' before split
- Path=Path[1:]
-
- result_resolve_path = Path.split('/')
- _context_name=[]
- for i in range(len(result_resolve_path)-1):
- _context_name.append(CosNaming.NameComponent(result_resolve_path[i],"dir"))
- _context_name.append(CosNaming.NameComponent(result_resolve_path[len(result_resolve_path)-1],"object"))
- try:
- self._obj = self._current_context.resolve(_context_name)
- except CosNaming.NamingContext.NotFound as ex:
- MESSAGE ( "Resolve : CosNaming.NamingContext.NotFound" )
- self._obj = None
- except CosNaming.NamingContext.InvalidName as ex:
- MESSAGE ( "Resolve : CosNaming.NamingContext.InvalidName" )
- self._obj = None
- except CosNaming.NamingContext.CannotProceed as ex:
- MESSAGE ( "Resolve : CosNaming.NamingContext.CannotProceed" )
- self._obj = None
- except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
- MESSAGE ( "Resolve : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" )
- self._obj = None
- return self._obj
-
- #-------------------------------------------------------------------------
-
- def Resolve_Dir(self, Path):
- """ ns.Resolve_Dir(pathname) -> dir
-
- find a CORBA object (ior) by its pathname
- """
- #MESSAGE ( "SALOME_NamingServicePy_i::Resolve" )
- path_list = list(Path)
- if path_list[0]=='/':
- self._current_context = self._root_context
- #delete first '/' before split
- Path=Path[1:]
-
- result_resolve_path = Path.split('/')
- _context_name=[]
- for i in range(len(result_resolve_path)-1):
- _context_name.append(CosNaming.NameComponent(result_resolve_path[i],"dir"))
- _context_name.append(CosNaming.NameComponent(result_resolve_path[len(result_resolve_path)-1],"dir"))
- print(_context_name)
- return None
- try:
- self._obj = self._current_context.resolve(_context_name)
- except CosNaming.NamingContext.NotFound as ex:
- MESSAGE ( "Resolve : CosNaming.NamingContext.NotFound" )
- self._obj = None
- except CosNaming.NamingContext.InvalidName as ex:
- MESSAGE ( "Resolve : CosNaming.NamingContext.InvalidName" )
- self._obj = None
- except CosNaming.NamingContext.CannotProceed as ex:
- MESSAGE ( "Resolve : CosNaming.NamingContext.CannotProceed" )
- self._obj = None
- except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
- MESSAGE ( "Resolve : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" )
- self._obj = None
- return self._obj
-
-
- #-------------------------------------------------------------------------
-
- def Create_Directory(self,ObjRef, Path):
- """ ns.Create_Directory(ObjRef, Path)
-
- create a sub directory
- """
- MESSAGE ( "SALOME_NamingServicePy_i::Create_Directory" )
- _not_exist = 0
- path_list = list(Path)
- if path_list[0]=='/':
- self._current_context = self._root_context
- #delete first '/' before split
- Path=Path[1:]
-
- result_resolve_path = Path.split('/')
- _context_name = []
- for i in range(len(result_resolve_path)):
- _context_name[CosNaming.NameComponent(result_resolve_path[i],"dir")]
- try:
- obj = self._current_context.resolve(_context_name)
- self._current_context = obj._narrow(CosNaming.NamingContext)
- except CosNaming.NamingContext.NotFound as ex:
- self._current_context = self._current_context.bind_new_context(_context_name)
- except CosNaming.NamingContext.InvalidName as ex:
- MESSAGE ( "Create_Directory : CosNaming.NamingContext.InvalidName" )
- except CosNaming.NamingContext.CannotProceed as ex:
- MESSAGE ( "Create_Directory : CosNaming.NamingContext.CannotProceed" )
- except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
- MESSAGE ( "Create_Directory : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" )
-
- def Destroy_Name(self,Path):
- """ ns.Destroy_Name(Path)
-
- remove a name in naming service
- """
- resolve_path=Path.split('/')
- if resolve_path[0] == '': del resolve_path[0]
- dir_path=resolve_path[:-1]
- context_name=[]
- for e in dir_path:
- context_name.append(CosNaming.NameComponent(e,"dir"))
- context_name.append(CosNaming.NameComponent(resolve_path[-1],"object"))
-
- try:
- self._root_context.unbind(context_name)
- except CosNaming.NamingContext.NotFound as ex:
- return
- except CORBA.Exception as ex:
- return
-
- def Destroy_FullDirectory(self,Path):
- """ ns.Destroy_FullDirectory(Path)
-
- remove recursively a directory
- """
- context_name=[]
- for e in Path.split('/'):
- if e == '':continue
- context_name.append(CosNaming.NameComponent(e,"dir"))
-
- try:
- context=self._root_context.resolve(context_name)
- except CosNaming.NamingContext.NotFound as ex:
- return
- except CORBA.Exception as ex:
- return
-
- bl,bi=context.list(0)
- if bi is not None:
- ok,b=bi.next_one()
- while(ok):
- for s in b.binding_name :
- if s.kind == "object":
- context.unbind([s])
- elif s.kind == "dir":
- context.unbind([s])
- ok,b=bi.next_one()
-
- context.destroy()
- self._root_context.unbind(context_name)
+#! /usr/bin/env python3\r
+# -*- coding: iso-8859-1 -*-\r
+# Copyright (C) 2007-2020 CEA/DEN, EDF R&D, OPEN CASCADE\r
+#\r
+# Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,\r
+# CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS\r
+#\r
+# This library is free software; you can redistribute it and/or\r
+# modify it under the terms of the GNU Lesser General Public\r
+# License as published by the Free Software Foundation; either\r
+# version 2.1 of the License, or (at your option) any later version.\r
+#\r
+# This library is distributed in the hope that it will be useful,\r
+# but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r
+# Lesser General Public License for more details.\r
+#\r
+# You should have received a copy of the GNU Lesser General Public\r
+# License along with this library; if not, write to the Free Software\r
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+#\r
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com\r
+#\r
+\r
+# SALOME NamingService : wrapping NamingService services\r
+# File : SALOME_NamingServicePy.py\r
+# Author : Estelle Deville, CEA\r
+# Module : SALOME\r
+# $Header$\r
+## @package SALOME_NamingServicePy\r
+# \brief Module to manage SALOME naming service from python\r
+#\r
+import sys\r
+import time\r
+from omniORB import CORBA\r
+import CosNaming\r
+import string\r
+from string import *\r
+\r
+from SALOME_utilities import *\r
+#=============================================================================\r
+\r
+class SALOME_NamingServicePy_i(object):\r
+ """\r
+ A class to manage SALOME naming service from python code\r
+ """\r
+ _orb = None\r
+ _root_context=None\r
+ _current_context=None\r
+ _obj=None\r
+ \r
+ #-------------------------------------------------------------------------\r
+\r
+ def __init__(self, orb=None, steps=240, spy=False):\r
+ """\r
+ Standard Constructor, with ORB reference.\r
+ \r
+ Initializes the naming service root context\r
+ """\r
+ #MESSAGE ( "SALOME_NamingServicePy_i::__init__" )\r
+ if orb is None:\r
+ orb=CORBA.ORB_init([''], CORBA.ORB_ID)\r
+ self._orb = orb\r
+ # initialize root context and current context\r
+ ok = 0\r
+ while steps > 0 and ok == 0:\r
+ try:\r
+ obj =self._orb.resolve_initial_references("NameService")\r
+ self._root_context =obj._narrow(CosNaming.NamingContext)\r
+ self._current_context = self._root_context\r
+\r
+ \r
+ if self._root_context is None :\r
+ #MESSAGE ( "Name Service Reference is invalid" )\r
+ #sys.exit(1)\r
+ MESSAGE(" Name service not found")\r
+ else:\r
+ ok = 1\r
+ except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):\r
+ MESSAGE(" Name service not found")\r
+ time.sleep(0.25)\r
+ steps = steps - 1\r
+ if steps == 0 and self._root_context is None: \r
+ MESSAGE ( "Name Service Reference is invalid" )\r
+ if spy:\r
+ raise ValueError("Name Service Reference is invalid")\r
+ else:\r
+ sys.exit(1)\r
+\r
+ #-------------------------------------------------------------------------\r
+\r
+ def Register(self,ObjRef, Path):\r
+ """ ns.Register(object,pathname ) \r
+ \r
+ register a CORBA object under a pathname\r
+ """\r
+\r
+ MESSAGE ( "SALOME_NamingServicePy_i::Register" )\r
+ _not_exist = 0\r
+ path_list = list(Path)\r
+ if path_list[0]=='/':\r
+ self._current_context = self._root_context\r
+ #delete first '/' before split\r
+ Path=Path[1:]\r
+\r
+ result_resolve_path = Path.split('/')\r
+ if len(result_resolve_path)>1:\r
+ # A directory is treated (not only an object name)\r
+ # We had to test if the directory where ObjRef should be recorded \r
+ # is already done\r
+ # If not, the new context has to be created\r
+ _context_name = []\r
+ for i in range(len(result_resolve_path)-1):\r
+ _context_name.append(CosNaming.NameComponent(result_resolve_path[i],"dir"))\r
+ \r
+ try:\r
+ obj = self._current_context.resolve(_context_name)\r
+ self._current_context = obj._narrow(CosNaming.NamingContext)\r
+ except CosNaming.NamingContext.NotFound as ex:\r
+ _not_exist = 1\r
+ except CosNaming.NamingContext.InvalidName as ex:\r
+ MESSAGE ( "Register : CosNaming.NamingContext.InvalidName" )\r
+ except CosNaming.NamingContext.CannotProceed as ex:\r
+ MESSAGE ( "Register : CosNaming.NamingContext.CannotProceed" )\r
+ except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):\r
+ MESSAGE ( "Register : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" )\r
+\r
+ if _not_exist:\r
+ # at least one context of the complete path is not created, we had\r
+ # to create it or them\r
+ _context_name = []\r
+ for i in range(len(result_resolve_path)-1):\r
+ _context_name = [CosNaming.NameComponent(result_resolve_path[i],"dir")]\r
+\r
+ try:\r
+ obj = self._current_context.resolve(_context_name)\r
+ self._current_context = obj._narrow(CosNaming.NamingContext)\r
+ except CosNaming.NamingContext.NotFound as ex:\r
+ #This context is not created. It will be done\r
+ self._current_context = self._current_context.bind_new_context(_context_name)\r
+\r
+ #The current directory is now the directory where the object should \r
+ #be recorded\r
+ \r
+ _context_name = [CosNaming.NameComponent(result_resolve_path[len(result_resolve_path)-1],"object")]\r
+ try:\r
+ self._current_context.bind(_context_name,ObjRef)\r
+ except CosNaming.NamingContext.NotFound as ex:\r
+ MESSAGE ( "Register : CosNaming.NamingContext.NotFound" )\r
+ except CosNaming.NamingContext.InvalidName as ex:\r
+ MESSAGE ( "Register : CosNaming.NamingContext.InvalidName" )\r
+ except CosNaming.NamingContext.CannotProceed as ex:\r
+ MESSAGE ( "Register : CosNaming.NamingContext.CannotProceed" )\r
+ except CosNaming.NamingContext.AlreadyBound as ex:\r
+ MESSAGE ( "Register : CosNaming.NamingContext.AlreadyBound, object will be rebind" )\r
+ self._current_context.rebind(_context_name,ObjRef)\r
+ except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):\r
+ MESSAGE ( "Register : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" )\r
+\r
+ #-------------------------------------------------------------------------\r
+\r
+ def Resolve(self, Path):\r
+ """ ns.Resolve(pathname) -> object\r
+\r
+ find a CORBA object (ior) by its pathname\r
+ """\r
+ #MESSAGE ( "SALOME_NamingServicePy_i::Resolve" )\r
+ path_list = list(Path)\r
+ if path_list[0]=='/':\r
+ self._current_context = self._root_context\r
+ #delete first '/' before split\r
+ Path=Path[1:]\r
+\r
+ result_resolve_path = Path.split('/')\r
+ _context_name=[]\r
+ for i in range(len(result_resolve_path)-1):\r
+ _context_name.append(CosNaming.NameComponent(result_resolve_path[i],"dir"))\r
+ _context_name.append(CosNaming.NameComponent(result_resolve_path[len(result_resolve_path)-1],"object"))\r
+ try:\r
+ self._obj = self._current_context.resolve(_context_name)\r
+ except CosNaming.NamingContext.NotFound as ex:\r
+ MESSAGE ( "Resolve : CosNaming.NamingContext.NotFound" )\r
+ self._obj = None\r
+ except CosNaming.NamingContext.InvalidName as ex:\r
+ MESSAGE ( "Resolve : CosNaming.NamingContext.InvalidName" )\r
+ self._obj = None\r
+ except CosNaming.NamingContext.CannotProceed as ex:\r
+ MESSAGE ( "Resolve : CosNaming.NamingContext.CannotProceed" )\r
+ self._obj = None\r
+ except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):\r
+ MESSAGE ( "Resolve : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" )\r
+ self._obj = None\r
+ return self._obj\r
+\r
+ #-------------------------------------------------------------------------\r
+\r
+ def Resolve_Dir(self, Path):\r
+ """ ns.Resolve_Dir(pathname) -> dir\r
+\r
+ find a CORBA object (ior) by its pathname\r
+ """\r
+ #MESSAGE ( "SALOME_NamingServicePy_i::Resolve" )\r
+ path_list = list(Path)\r
+ if path_list[0]=='/':\r
+ self._current_context = self._root_context\r
+ #delete first '/' before split\r
+ Path=Path[1:]\r
+\r
+ result_resolve_path = Path.split('/')\r
+ _context_name=[]\r
+ for i in range(len(result_resolve_path)-1):\r
+ _context_name.append(CosNaming.NameComponent(result_resolve_path[i],"dir"))\r
+ _context_name.append(CosNaming.NameComponent(result_resolve_path[len(result_resolve_path)-1],"dir"))\r
+ print(_context_name)\r
+ return None\r
+ try:\r
+ self._obj = self._current_context.resolve(_context_name)\r
+ except CosNaming.NamingContext.NotFound as ex:\r
+ MESSAGE ( "Resolve : CosNaming.NamingContext.NotFound" )\r
+ self._obj = None\r
+ except CosNaming.NamingContext.InvalidName as ex:\r
+ MESSAGE ( "Resolve : CosNaming.NamingContext.InvalidName" )\r
+ self._obj = None\r
+ except CosNaming.NamingContext.CannotProceed as ex:\r
+ MESSAGE ( "Resolve : CosNaming.NamingContext.CannotProceed" )\r
+ self._obj = None\r
+ except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):\r
+ MESSAGE ( "Resolve : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" )\r
+ self._obj = None\r
+ return self._obj\r
+\r
+\r
+ #-------------------------------------------------------------------------\r
+\r
+ def Create_Directory(self,ObjRef, Path):\r
+ """ ns.Create_Directory(ObjRef, Path) \r
+\r
+ create a sub directory \r
+ """\r
+ MESSAGE ( "SALOME_NamingServicePy_i::Create_Directory" )\r
+ _not_exist = 0\r
+ path_list = list(Path)\r
+ if path_list[0]=='/':\r
+ self._current_context = self._root_context\r
+ #delete first '/' before split\r
+ Path=Path[1:]\r
+\r
+ result_resolve_path = Path.split('/')\r
+ _context_name = []\r
+ for i in range(len(result_resolve_path)):\r
+ _context_name[CosNaming.NameComponent(result_resolve_path[i],"dir")] \r
+ try:\r
+ obj = self._current_context.resolve(_context_name)\r
+ self._current_context = obj._narrow(CosNaming.NamingContext)\r
+ except CosNaming.NamingContext.NotFound as ex:\r
+ self._current_context = self._current_context.bind_new_context(_context_name)\r
+ except CosNaming.NamingContext.InvalidName as ex:\r
+ MESSAGE ( "Create_Directory : CosNaming.NamingContext.InvalidName" )\r
+ except CosNaming.NamingContext.CannotProceed as ex:\r
+ MESSAGE ( "Create_Directory : CosNaming.NamingContext.CannotProceed" )\r
+ except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):\r
+ MESSAGE ( "Create_Directory : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" )\r
+ \r
+ def Destroy_Name(self,Path):\r
+ """ ns.Destroy_Name(Path) \r
+\r
+ remove a name in naming service\r
+ """\r
+ resolve_path=Path.split('/')\r
+ if resolve_path[0] == '': del resolve_path[0]\r
+ dir_path=resolve_path[:-1]\r
+ context_name=[]\r
+ for e in dir_path:\r
+ context_name.append(CosNaming.NameComponent(e,"dir"))\r
+ context_name.append(CosNaming.NameComponent(resolve_path[-1],"object"))\r
+ \r
+ try:\r
+ self._root_context.unbind(context_name)\r
+ except CosNaming.NamingContext.NotFound as ex:\r
+ return\r
+ except CORBA.Exception as ex:\r
+ return\r
+\r
+ def Destroy_FullDirectory(self,Path):\r
+ """ ns.Destroy_FullDirectory(Path)\r
+\r
+ remove recursively a directory\r
+ """\r
+ context_name=[]\r
+ for e in Path.split('/'):\r
+ if e == '':continue\r
+ context_name.append(CosNaming.NameComponent(e,"dir"))\r
+\r
+ try:\r
+ context=self._root_context.resolve(context_name)\r
+ except CosNaming.NamingContext.NotFound as ex:\r
+ return\r
+ except CORBA.Exception as ex:\r
+ return\r
+\r
+ bl,bi=context.list(0)\r
+ if bi is not None:\r
+ ok,b=bi.next_one()\r
+ while(ok):\r
+ for s in b.binding_name :\r
+ if s.kind == "object":\r
+ context.unbind([s])\r
+ elif s.kind == "dir":\r
+ context.unbind([s])\r
+ ok,b=bi.next_one()\r
+\r
+ context.destroy()\r
+ self._root_context.unbind(context_name)\r