Salome HOME
Code improvements, review and simplifications (2)
[modules/adao.git] / src / daComposant / daCore / PlatformInfo.py
index 61927537bdede286498cc7ff436c821ca0b3922a..3a01d6a268852e56de7d0328693dde2c6b368313 100644 (file)
@@ -1,6 +1,6 @@
 # -*- coding: utf-8 -*-
 #
-# Copyright (C) 2008-2018 EDF R&D
+# Copyright (C) 2008-2022 EDF R&D
 #
 # This library is free software; you can redistribute it and/or
 # modify it under the terms of the GNU Lesser General Public
 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
 
 """
-    Informations sur le code et la plateforme, et mise à jour des chemins
+    Informations sur le code et la plateforme, et mise à jour des chemins.
 
     La classe "PlatformInfo" permet de récupérer les informations générales sur
     le code et la plateforme sous forme de strings, ou d'afficher directement
     les informations disponibles par les méthodes. L'impression directe d'un
     objet de cette classe affiche les informations minimales. Par exemple :
-        print PlatformInfo()
-        print PlatformInfo().getVersion()
+        print(PlatformInfo())
+        print(PlatformInfo().getVersion())
         created = PlatformInfo().getDate()
 
     La classe "PathManagement" permet de mettre à jour les chemins système pour
@@ -46,6 +46,10 @@ __all__ = []
 
 import os
 import sys
+import platform
+import locale
+import logging
+import re
 
 # ==============================================================================
 class PlatformInfo(object):
@@ -71,6 +75,63 @@ class PlatformInfo(object):
         import daCore.version as dav
         return dav.date
 
+    def getYear(self):
+        "Retourne l'année de création de la version"
+        import daCore.version as dav
+        return dav.year
+
+    def getSystemInformation(self, __prefix=""):
+        __msg  = ""
+        __msg += "\n%s%30s : %s" %(__prefix,"platform.system",platform.system())
+        __msg += "\n%s%30s : %s" %(__prefix,"sys.platform",sys.platform)
+        __msg += "\n%s%30s : %s" %(__prefix,"platform.version",platform.version())
+        __msg += "\n%s%30s : %s" %(__prefix,"platform.platform",platform.platform())
+        __msg += "\n%s%30s : %s" %(__prefix,"platform.machine",platform.machine())
+        if len(platform.processor())>0:
+            __msg += "\n%s%30s : %s" %(__prefix,"platform.processor",platform.processor())
+        #
+        if sys.platform.startswith('linux'):
+            if hasattr(platform, 'linux_distribution'):
+                __msg += "\n%s%30s : %s" %(__prefix,
+                    "platform.linux_distribution",str(platform.linux_distribution()))
+            elif hasattr(platform, 'dist'):
+                __msg += "\n%s%30s : %s" %(__prefix,"platform.dist",str(platform.dist()))
+        elif sys.platform.startswith('darwin'):
+            if hasattr(platform, 'mac_ver'):
+                __macosxv = {
+                     '0': 'Cheetah',       '1': 'Puma',         '2': 'Jaguar',
+                     '3': 'Panther',       '4': 'Tiger',        '5': 'Leopard',
+                     '6': 'Snow Leopard',  '7': 'Lion',         '8': 'Mountain Lion',
+                     '9': 'Mavericks',    '10': 'Yosemite',    '11': 'El Capitan',
+                    '12': 'Sierra',       '13': 'High Sierra', '14': 'Mojave',
+                    '15': 'Catalina',     '16': 'Big Sur',     '17': 'Monterey',
+                    }
+                for key in __macosxv:
+                    if (platform.mac_ver()[0].split('.')[1] == key):
+                        __msg += "\n%s%30s : %s" %(__prefix,
+                            "platform.mac_ver",str(platform.mac_ver()[0]+"(" + __macosxv[key]+")"))
+            elif hasattr(platform, 'dist'):
+                __msg += "\n%s%30s : %s" %(__prefix,"platform.dist",str(platform.dist()))
+        elif os.name == 'nt':
+            __msg += "\n%s%30s : %s" %(__prefix,"platform.win32_ver",platform.win32_ver()[1])
+        #
+        __msg += "\n"
+        __msg += "\n%s%30s : %s" %(__prefix,"platform.python_implementation",platform.python_implementation())
+        __msg += "\n%s%30s : %s" %(__prefix,"sys.executable",sys.executable)
+        __msg += "\n%s%30s : %s" %(__prefix,"sys.version",sys.version.replace('\n',''))
+        __msg += "\n%s%30s : %s" %(__prefix,"sys.getfilesystemencoding",str(sys.getfilesystemencoding()))
+        __msg += "\n%s%30s : %s" %(__prefix,"locale.getdefaultlocale",str(locale.getdefaultlocale()))
+        __msg += "\n"
+        __msg += "\n%s%30s : %s" %(__prefix,"os.cpu_count",os.cpu_count())
+        if hasattr(os, 'sched_getaffinity'):
+            __msg += "\n%s%30s : %s" %(__prefix,"len(os.sched_getaffinity(0))",len(os.sched_getaffinity(0)))
+        else:
+            __msg += "\n%s%30s : %s" %(__prefix,"len(os.sched_getaffinity(0))","Unsupported on this platform")
+        __msg += "\n"
+        __msg += "\n%s%30s : %s" %(__prefix,"platform.node",platform.node())
+        __msg += "\n%s%30s : %s" %(__prefix,"os.path.expanduser",os.path.expanduser('~'))
+        return __msg
+
     def getPythonVersion(self):
         "Retourne la version de python disponible"
         return ".".join([str(x) for x in sys.version_info[0:3]]) # map(str,sys.version_info[0:3]))
@@ -183,18 +244,122 @@ try:
 except ImportError:
     has_nlopt = False
 
+try:
+    import sdf
+    has_sdf = True
+except ImportError:
+    has_sdf = False
+
 has_salome = bool( "ROOT_SALOME"   in os.environ )
 has_yacs   = bool( "YACS_ROOT_DIR" in os.environ )
 has_adao   = bool( "ADAO_ROOT_DIR" in os.environ )
 has_eficas = bool( "EFICAS_ROOT_DIR" in os.environ )
 
 # ==============================================================================
-def uniq(sequence):
+def uniq( __sequence ):
     """
     Fonction pour rendre unique chaque élément d'une liste, en préservant l'ordre
     """
     __seen = set()
-    return [x for x in sequence if x not in __seen and not __seen.add(x)]
+    return [x for x in __sequence if x not in __seen and not __seen.add(x)]
+
+def isIterable( __sequence, __check = False, __header = "" ):
+    """
+    Vérification que l'argument est un itérable interne.
+    Remarque : pour permettre le test correct en MultiFonctions,
+    - Ne pas accepter comme itérable un "numpy.ndarray"
+    - Ne pas accepter comme itérable avec hasattr(__sequence, "__iter__")
+    """
+    if  isinstance( __sequence, (list, tuple, map, dict) ):
+        __isOk = True
+    elif type(__sequence).__name__ in ('generator','range'):
+        __isOk = True
+    elif "_iterator" in type(__sequence).__name__:
+        __isOk = True
+    else:
+        __isOk = False
+    if __check and not __isOk:
+        raise TypeError("Not iterable or unkown input type%s: %s"%(__header, type(__sequence),))
+    return __isOk
+
+def date2int( __date, __lang="FR" ):
+    """
+    Fonction de secours, conversion pure : dd/mm/yy hh:mm ---> int(yyyymmddhhmm)
+    """
+    __date = __date.strip()
+    if __date.count('/') == 2 and __date.count(':') == 0 and __date.count(' ') == 0:
+        d,m,y = __date.split("/")
+        __number = (10**4)*int(y)+(10**2)*int(m)+int(d)
+    elif __date.count('/') == 2 and __date.count(':') == 1 and __date.count(' ') > 0:
+        part1, part2 = __date.split()
+        d,m,y = part1.strip().split("/")
+        h,n   = part2.strip().split(":")
+        __number = (10**8)*int(y)+(10**6)*int(m)+(10**4)*int(d)+(10**2)*int(h)+int(n)
+    else:
+        raise ValueError("Cannot convert \"%s\" as a D/M/Y H:M date"%d)
+    return __number
+
+def strvect2liststr( __strvect ):
+    """
+    Fonction de secours, conversion d'une chaîne de caractères de
+    représentation de vecteur en une liste de chaînes de caractères de
+    représentation de flottants
+    """
+    for s in ("array", "matrix", "list", "tuple", "[", "]", "(", ")"):
+        __strvect = __strvect.replace(s,"")  # Rien
+    for s in (",", ";"):
+        __strvect = __strvect.replace(s," ") # Blanc
+    return __strvect.split()
+
+def strmatrix2liststr( __strvect ):
+    """
+    Fonction de secours, conversion d'une chaîne de caractères de
+    représentation de matrice en une liste de chaînes de caractères de
+    représentation de flottants
+    """
+    for s in ("array", "matrix", "list", "tuple", "[", "(", "'", '"'):
+        __strvect = __strvect.replace(s,"")  # Rien
+    __strvect = __strvect.replace(","," ") # Blanc
+    for s in ("]", ")"):
+        __strvect = __strvect.replace(s,";") # "]" et ")" par ";"
+    __strvect = re.sub(';\s*;',';',__strvect)
+    __strvect = __strvect.rstrip(";") # Après ^ et avant v
+    __strmat = [l.split() for l in __strvect.split(";")]
+    return __strmat
+
+def checkFileNameConformity( __filename, __warnInsteadOfPrint=True ):
+    if sys.platform.startswith("win") and len(__filename) > 256:
+        __conform = False
+        __msg = (" For some shared or older file systems on Windows, a file "+\
+            "name longer than 256 characters can lead to access problems."+\
+            "\n  The name of the file in question is the following:"+\
+            "\n  %s")%(__filename,)
+        if __warnInsteadOfPrint: logging.warning(__msg)
+        else:                    print(__msg)
+    else:
+        __conform = True
+    #
+    return __conform
+
+def checkFileNameImportability( __filename, __warnInsteadOfPrint=True ):
+    if str(__filename).count(".") > 1:
+        __conform = False
+        __msg = (" The file name contains %i point(s) before the extension "+\
+            "separator, which can potentially lead to problems when "+\
+            "importing this file into Python, as it can then be recognized "+\
+            "as a sub-module (generating a \"ModuleNotFoundError\"). If it "+\
+            "is intentional, make sure that there is no module with the "+\
+            "same name as the part before the first point, and that there is "+\
+            "no \"__init__.py\" file in the same directory."+\
+            "\n  The name of the file in question is the following:"+\
+            "\n  %s")%(int(str(__filename).count(".")-1), __filename)
+        if __warnInsteadOfPrint is None: pass
+        elif __warnInsteadOfPrint:       logging.warning(__msg)
+        else:                            print(__msg)
+    else:
+        __conform = True
+    #
+    return __conform
 
 # ==============================================================================
 class PathManagement(object):
@@ -322,4 +487,4 @@ class SystemUsage(object):
 
 # ==============================================================================
 if __name__ == "__main__":
-    print('\n AUTODIAGNOSTIC \n')
+    print('\n AUTODIAGNOSTIC\n')