Salome HOME
Avoid FileNotFound exception
[modules/kernel.git] / bin / salome_utils.py
index df4a49eb55ae483dc61a64571612306705cc7cbd..346db515ac7948fe4706e8ec5382752b72624d0b 100644 (file)
@@ -116,8 +116,14 @@ def getUserName():
 
     :return user name
     """
-    return os.getenv('USERNAME', 'unknown') if sys.platform == 'win32' \
-        else os.getenv('USER', os.getenv('LOGNAME', 'unknown'))
+    if sys.platform == 'win32':
+        username = os.getenv('USERNAME')
+    else:
+        username = os.getenv('USER', os.getenv('LOGNAME'))
+    if username is None:
+        import getpass
+        username = getpass.getuser()
+    return username
 
 # ---
 
@@ -170,6 +176,9 @@ def getAppName():
     """
     return os.getenv('APPNAME', 'SALOME') # 'SALOME' is default user name
 
+def getPid():
+    return os.getpid()
+
 # ---
 
 def getPortNumber(use_default=True):
@@ -246,6 +255,7 @@ def generateFileName(path, prefix=None, suffix=None, extension=None,
     - with_hostname : use host name:
     - with_port : use port number:
     - with_app      : use application name:
+    - with_pid      : use current pid
 
     Any of these keyword arguments can accept either explicit string value,
     or `True` to automatically deduce value from current configuration.
@@ -270,6 +280,7 @@ def generateFileName(path, prefix=None, suffix=None, extension=None,
     _with_kwarg('with_hostname', getShortHostName)
     _with_kwarg('with_port', getPortNumber)
     _with_kwarg('with_app', getAppName)
+    _with_kwarg('with_pid', getPid)
     _with_str(suffix)
 
     # raise an exception if file name is empty
@@ -325,6 +336,22 @@ def cleanDir(path):
 
 # ---
 
+def makeDir(path, mode=0o777):
+    """
+    Make directory with the specified path.
+    :param path : directory path
+    :param mode : access mode
+    """
+    try:
+        oldmask = os.umask(0)
+        os.makedirs(path, mode=mode, exist_ok=True)
+    except IOError:
+        pass
+    finally:
+        os.umask(oldmask)
+
+# ---
+
 def makeTmpDir(path, mode=0o777):
     """
     Make temporary directory with the specified path.
@@ -332,8 +359,7 @@ def makeTmpDir(path, mode=0o777):
     :param path : directory path
     :param mode : access mode
     """
-    with suppress(OSError):
-        os.makedirs(path, mode=mode, exist_ok=True)
+    makeDir(path, mode)
     cleanDir(path)
 
 # ---
@@ -436,7 +462,7 @@ def getOmniNamesPid(port):
     """
     processes = {p.info['pid']: p.info['name'] for p in psutil.process_iter(['pid', 'name'])}
     return next((c.pid for c in psutil.net_connections(kind='inet') \
-                     if c.laddr.port == port and processes.get(c.pid) == 'omniNames'), None)
+                     if str(c.laddr.port) == str(port) and processes.get(c.pid).startswith('omniNames')), None)
 # --
 
 def killOmniNames(port):