From c3f9e91c2f331da7df750618392cc1d4fb76a7ce Mon Sep 17 00:00:00 2001 From: =?utf8?q?C=C3=A9dric=20Aguerre?= Date: Wed, 20 May 2015 17:20:00 +0200 Subject: [PATCH] salome info & salome connect --- bin/ORBConfigFile.py | 17 +++ bin/appliskel/.salome-completion.sh | 8 +- bin/runConsole.py | 198 ++++++++++++++++++++++++++-- bin/salomeConsole.py | 36 +++-- bin/salomeContext.py | 44 +++++-- 5 files changed, 270 insertions(+), 33 deletions(-) diff --git a/bin/ORBConfigFile.py b/bin/ORBConfigFile.py index 0f7e16881..96760c729 100644 --- a/bin/ORBConfigFile.py +++ b/bin/ORBConfigFile.py @@ -22,6 +22,23 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # +def readORBConfigFile(filename): + """ Extract information (host, port) from ORB configuration file. """ + with open(filename) as f: + contents = f.readlines() + + import re + host, port = None, None + for line in contents: + m = re.match("(ORB)?InitRef = NameService=corbaname::([\D\d]+):(\d*)", line) + if m: + host = m.group(2) + port = m.group(3) + break + pass + return host, port +# + # IMPORTANT NOTE: do not add any print call (cf. note at the bottom of the file) def writeORBConfigFile(path, host, port, kwargs={}): diff --git a/bin/appliskel/.salome-completion.sh b/bin/appliskel/.salome-completion.sh index 705129f83..9725b6f60 100644 --- a/bin/appliskel/.salome-completion.sh +++ b/bin/appliskel/.salome-completion.sh @@ -51,7 +51,7 @@ _salome() local cur prev command options COMPREPLY=( ) _get_comp_words_by_ref -n = cur prev - commands='start context shell connect kill killall test info help coffee' + commands='start context shell connect kill killall test info help coffee car' # Algorithm: # If cursor is at index 1 @@ -76,6 +76,12 @@ _salome() shell) options='-h --help -p --port= -m --machine= -d --directory= -u --user= --with-mpi-module=' ;; + info) + options='-h --help -p --ports -v --version' + ;; + connect) + options='-h --help -c -p' + ;; esac COMPREPLY=( $( compgen -W "$options" -- "$cur" ) ) fi diff --git a/bin/runConsole.py b/bin/runConsole.py index 83d6356f6..337b1eb94 100644 --- a/bin/runConsole.py +++ b/bin/runConsole.py @@ -21,7 +21,158 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -def __prompt(environment = None, commands=None, message = "Connecting to SALOME"): +from optparse import OptionParser +import os +import sys +import user +import pickle + +# Use to display newlines (\n) in epilog +class MyParser(OptionParser): + def format_epilog(self, formatter): + return self.epilog +# + +def __parse_args(args): + if args is None: + args = [] + + usage = "Usage: salome connect [-p port] [ -c command | script | - ]" + epilog = """ +Connects a Python console to a local SALOME instance.\n +If port is given, try to connect to corresponding instance. +If port is not given, or does not correspond to a running instance, +ask user to select a port from list of available SALOME instances.\n + +The -c option can be used to specify the command to execute in the interpreter. +A script can also be used. +For example: + salome connect -p 2810 -c 'print "Hello"' + salome connect -p 2810 hello.py +""" + parser = MyParser(usage=usage, epilog=epilog) + parser.add_option("-p", metavar="", default=0, + action="store", type="string", dest="port", + help="The port to connect to." + ) + parser.add_option('-c', dest="command", default=None, + help="The command to execute in the interpreter." + ) + try: + (options, args) = parser.parse_args(args) + except Exception, e: + print e + return + + return options, args +# + +def __show_running_instances(list_of_instances): + print '-'*10 + print "Running instances:" + for i in range(len(list_of_instances)): + host, port, _ = list_of_instances[i] + print " [%d] %s:%s"%(i+1, host, port) + print '-'*10 +# + +def __choose_in(choices): + __show_running_instances(choices) + rep = raw_input("Please enter the number of instance to use (0 to cancel): ") + if rep == '0': + return None, None, None + elif rep in [str(i) for i in range(1, len(choices)+1)]: + return choices[int(rep)-1] + else: + print "*** Invalid number! ***" + return __choose_in(choices) +# + +def __get_running_session(requested_port=None, lastInstanceByDefault=False): + import glob + import salome_utils + from ORBConfigFile import readORBConfigFile + + omniorbUserPath = os.getenv("OMNIORB_USER_PATH") + files = glob.glob(os.path.join(omniorbUserPath,".omniORB_"+salome_utils.getUserName()+"_*[!last].cfg")) + available_connexions = [] + for filename in files: + host, port = readORBConfigFile(filename) + available_connexions.append((host, port, filename)) + + host, port, filename = None, None, None + if requested_port: + print "Search for running instance on port %s..."%requested_port + found = [(h,p,f) for h,p,f in available_connexions if p == requested_port] + if not found: + print " ...no running instance found" + elif len(found) == 1: + host, port, filename = found[0] + print " ...found unique instance: %s:%s"%(host,port) + else: + print " ...multiple instances found ; please choose one in the following:" + host, port, filename = __choose_in(found) + else: # no requested port + if not available_connexions: + print "No running instance found" + elif len(available_connexions) == 1: + host, port, filename = available_connexions[0] + print "Found unique instance: %s:%s"%(host,port) + else: + print "Multiple instances found ; please choose one in the following:" + host, port, filename = __choose_in(available_connexions) + pass + + if port: + print "Selected instance: %s:%s"%(host, port) + else: + print "Cancel." + + return host, port, filename +# + +import CORBA +import CosNaming +import orbmodule + +class client(orbmodule.client): + def initNS(self,args): + # Obtain a reference to the root naming context + obj = self.orb.resolve_initial_references("NameService") + try: + self.rootContext = obj._narrow(CosNaming.NamingContext) + return + except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE): + print "It's not a valid naming service" + self.rootContext = None + sys.stdout.flush() + raise +# + +def start_client(): + print os.getenv("OMNIORB_CONFIG") + + try: + clt = client() + except Exception: + import traceback + traceback.print_exc() + sys.exit(1) + # + + session_server = clt.Resolve('/Kernel/Session') + if session_server: + session = clt.waitNS("/Kernel/Session") + catalog = clt.waitNS("/Kernel/ModulCatalog") + studyMgr = clt.waitNS("/myStudyManager") + + import salome + salome.salome_init() + from salome import lcc + print "--> now connected to SALOME" +# + +def _prompt(environment=None, commands=None, message="Connecting to SALOME"): if environment is None: environment = globals().copy() environment.update(locals()) @@ -29,20 +180,51 @@ def __prompt(environment = None, commands=None, message = "Connecting to SALOME" commands = [] import code - import rlcompleter #@UnusedImport + import rlcompleter import readline + readline.set_completer(rlcompleter.Completer(environment).complete) readline.parse_and_bind("tab: complete") # calling this with globals ensures we can see the environment print message shell = code.InteractiveConsole(environment) for cmd in commands: + print "Execute command:", cmd shell.push(cmd) - return shell.interact + pass + shell.interact() # -def connect(args=None): - if args is None: - args = [] - p = __prompt(commands=["import salomeConsole"]) - p() +def connect(args=None, env=None): + if env is not None: + os.environ = env + options, args = __parse_args(args) + host, port, filename = __get_running_session(options.port) + if not port: + sys.exit(0) + + cmd = [ + "os.environ['OMNIORB_CONFIG'] = '%s'"%filename, + "start_client()" + ] + if options.command: + cmd.append(options.command) + if args: # unprocessed: may be scripts + for arg in args: + cmd.append("execfile('%s')"%os.path.abspath(os.path.expanduser(arg))) + + if port: + import subprocess + absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH','') + env_copy = os.environ.copy() + proc = subprocess.Popen(['python', os.path.join(absoluteAppliPath,"bin","salome","runConsole.py"), pickle.dumps(cmd)], shell=False, close_fds=True, env=env_copy) + return proc.communicate() +# + +if __name__ == "__main__": + if len(sys.argv) == 2: + cmd = pickle.loads(sys.argv[1]) + sys.argv = [] + _prompt(commands=cmd) + else: + print "runConsole.py: incorrect usage!" # diff --git a/bin/salomeConsole.py b/bin/salomeConsole.py index b4305d6f2..65248d45c 100755 --- a/bin/salomeConsole.py +++ b/bin/salomeConsole.py @@ -22,6 +22,14 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # +############################################### +############### IMPORTANT NOTE ################ +############################################### +# The salomeConsole.py script is obsolete. # +# Please consider the new salome launcher. # +############################################### + + import os import sys import glob @@ -36,7 +44,7 @@ import user #------------------------------- # Get major CORBA objects #------------------------------- -import CORBA +from omniORB import CORBA import CosNaming import salome_utils @@ -44,7 +52,7 @@ import orbmodule def getRunningSession(): omniorbUserPath = os.getenv("OMNIORB_USER_PATH") - files = glob.glob(os.path.join(omniorbUserPath,".omniORB_"+salome_utils.getUserName()+"_*.cfg")) + files = glob.glob(os.path.join(omniorbUserPath,".omniORB_"+salome_utils.getUserName()+"_*[!last].cfg")) filename="" if len(files)==1: @@ -70,16 +78,16 @@ def getRunningSession(): # class client(orbmodule.client): - def initNS(self,args): - # Obtain a reference to the root naming context - obj = self.orb.resolve_initial_references("NameService") - try: - self.rootContext = obj._narrow(CosNaming.NamingContext) - return - except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE): - print "It's not a valid naming service" - self.rootContext = None - raise + def initNS(self,args): + # Obtain a reference to the root naming context + obj = self.orb.resolve_initial_references("NameService") + try: + self.rootContext = obj._narrow(CosNaming.NamingContext) + return + except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE): + print "It's not a valid naming service" + self.rootContext = None + raise # def startClient(): @@ -92,7 +100,9 @@ def startClient(): clt.showNS() - session=clt.waitNS("/Kernel/Session") + session_server = clt.Resolve('/Kernel/Session') + if session_server: + session=clt.waitNS("/Kernel/Session") catalog=clt.waitNS("/Kernel/ModulCatalog") studyMgr=clt.waitNS("/myStudyManager") import salome diff --git a/bin/salomeContext.py b/bin/salomeContext.py index 84ab538d3..545e92979 100644 --- a/bin/salomeContext.py +++ b/bin/salomeContext.py @@ -33,8 +33,6 @@ import platform from salomeContextUtils import SalomeContextException def usage(): - #exeName = os.path.splitext(os.path.basename(__file__))[0] - msg = '''\ Usage: salome [command] [options] [--config=] @@ -51,14 +49,13 @@ Commands: test Run SALOME tests. info Display some information about SALOME help Show this message - coffee Yes! SALOME can also make coffee!! If no command is given, default to start. Command options: ================ Use salome --help to show help on command ; available for commands: - start, shell, test. + start, shell, connect, test, info. --config= ========================== @@ -383,13 +380,12 @@ class SalomeContext: if args is None: args = [] # Initialize SALOME environment - sys.argv = ['runConsole'] + args + sys.argv = ['runConsole'] import setenv setenv.main(True) - cmd = ["python", "-c", "import runConsole\nrunConsole.connect()" ] - proc = subprocess.Popen(cmd, shell=False, close_fds=True) - return proc.communicate() + import runConsole + return runConsole.connect(args) # def _kill(self, args=None): @@ -442,9 +438,35 @@ class SalomeContext: return runTests.runTests(args, exe="salome test") # - def _showInfo(self, unused=None): - print "Running with python", platform.python_version() - self._runAppli(["--version"]) + def _showInfo(self, args=None): + if args is None: + args = [] + + usage = "Usage: salome info [options]" + epilog = """\n +Display some information about SALOME.\n +Available options are: + -p,--ports Show list of busy ports (running SALOME instances). + -v,--version Show running SALOME version. + -h,--help Show this message. +""" + if not args: + args = ["--version"] + + if "-h" in args or "--help" in args: + print usage + epilog + return + + if "-p" in args or "--ports" in args: + import PortManager + ports = PortManager.getBusyPorts() + print "SALOME instances are running on ports:", ports + if ports: + print "Last started instance on port %s"%ports[-1] + + if "-v" in args or "--version" in args: + print "Running with python", platform.python_version() + self._runAppli(["--version"]) # def _usage(self, unused=None): -- 2.39.2