Salome HOME
Merge Python 3 porting.
[modules/kernel.git] / bin / salome_utils.py
index c19443595ca478b0aab6a5d7c3572bb7b9e1b59c..603b8168ce64d533acd0f7251d2b5cfcf97567df 100644 (file)
@@ -1,5 +1,5 @@
 #  -*- coding: iso-8859-1 -*-
-# Copyright (C) 2007-2015  CEA/DEN, EDF R&D, OPEN CASCADE
+# Copyright (C) 2007-2016  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
@@ -57,9 +57,9 @@ def _try_bool( arg ):
     If <arg> does not represent a boolean, an exception is raised.
     """
     import types
-    if type( arg ) == types.BooleanType  :
+    if type( arg ) == bool  :
         return arg
-    elif type( arg ) == types.StringType  :
+    elif type( arg ) == bytes  :
         v = str( arg ).lower()
         if   v in [ "yes", "y", "true"  ]: return True
         elif v in [ "no",  "n", "false" ]: return False
@@ -127,13 +127,17 @@ def getUserName():
     """
     Get user name:
     1. try USER environment variable (USERNAME on windows)
-    2. if fails, return 'unknown' as default user name
+    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:
-        return os.getenv("USER", "unknown")
+        user = os.getenv("USER")
+        if user:
+            return user
+        return os.getenv("LOGNAME", "unknown")
 # ---
 
 def getHostName():
@@ -144,7 +148,6 @@ def getHostName():
     3. if fails, try HOST environment variable
     4. if fails, return 'unknown' as default host name
     """
-    import os
     try:
         import socket
         host = socket.gethostname()
@@ -154,6 +157,11 @@ def getHostName():
     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
 
 # ---
@@ -286,7 +294,7 @@ def generateFileName( dir, prefix = None, suffix = None, extension = None,
     ### 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
+            print('Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw)
             pass
         pass
     ### process supported keywords
@@ -367,7 +375,7 @@ def generateFileName( dir, prefix = None, suffix = None, extension = None,
 
 # ---
 
-def makeTmpDir( path, mode=0777 ):
+def makeTmpDir( path, mode=0o777 ):
     """
     Make temporary directory with the specified path.
     If the directory exists then clear its contents.
@@ -480,3 +488,106 @@ def setVerbose(level):
     _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]
+        # 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
+# --