Obtenir les informations de la session

Les chemins du profil utilisateur LibreOffice et des modules partagés peuvent être combinés avec les langages Python ou Basic. Les emplacements des scripts BeanShell, Java, JavaScript et Python peuvent être dérivés de ces informations.

Exemple :

Avec le shell Python :

>>> from <the_module> import Session

>>> print(Session.SharedPythonScripts()) # methode statique

>>> print(Session().UserName) # propriété de l'objet

>>> input(Session().UserProfile) # propriété de l'objet

Depuis le menu Outils– Macros -Exécuter la macro... .


        from <the_module> import Session
            
        def demo_session():
            import screen_io as ui
            ui.MsgBox(Session.Share(),title='Installation Share')  # méthode staticque
            ui.Print(Session.SharedPythonScripts())  # méthode statique
            s = Session()  #  création de l'instance
            ui.MsgBox(s.UserName,title='Hello')  #propriété de l'objet
            ui.Print(s.UserPythonScripts)  # propriété de l'objet
            
        g_exportedScripts = (demo_session,)  # macros publiques
    

En Basic LibreOffice


        Sub Session_example()
            Dim s As New Session ' instance of Session class
            Print "Emplacement des scripts partagés :", s.SharedScripts
            MsgBox s.UserName,,"Hello"
            Print s.UserScripts, Chr(13), s.UserPythonScripts
        End Sub ' Session_example
    

Utilisation de COM / OLE et du langage de script Visual Basic.


        ' Le manager de service est toujours le point d'entrée
        ' S'il n'y a pas de bureau ouvert, un bureau est démarré
        Set sm = WScript.CreateObject("com.sun.star.ServiceManager")
        ' Le service PathSubstitution présente des informations à déduire
        ' emplacements depuis <UserProfile|Share>/Scripts/python
        Set obj = sm.createInstance("com.sun.star.util.PathSubstitution")
            
        MsgBox CreateObject("WScript.Network").UserName,, "Hello"
        user = obj.getSubstituteVariableValue("$(user)")
        MsgBox user & "/Scripts",, "User scripts location"
        libO = Replace(obj.getSubstituteVariableValue("$(inst)"), "program/..", "Share")
        MsgBox libO & "/Scripts",, "Shared scripts location"
    

Classe Session Python :


        import getpass, os, os.path, uno
            
        class Session():
            @staticmethod
            def substitute(var_name):
                ctx = uno.getComponentContext()
                ps = ctx.getServiceManager().createInstanceWithContext(
                    'com.sun.star.util.PathSubstitution', ctx)
                return ps.getSubstituteVariableValue(var_name)
            @staticmethod
            def Share():
                inst = uno.fileUrlToSystemPath(Session.substitute("$(prog)"))
                return os.path.normpath(inst.replace('program', "Share"))
            @staticmethod
            def SharedScripts():
                return ''.join([Session.Share(), os.sep, "Scripts"])
            @staticmethod
            def SharedPythonScripts():
                return ''.join([Session.SharedScripts(), os.sep, 'python'])
            @property  # alternative pour la variable '$(username)'
            def UserName(self): return getpass.getuser()
            @property
            def UserProfile(self):
                return uno.fileUrlToSystemPath(Session.substitute("$(user)"))
            @property
            def UserScripts(self):
                return ''.join([self.UserProfile, os.sep, 'Scripts'])
            @property
            def UserPythonScripts(self):
                return ''.join([self.UserScripts, os.sep, "python"])
    
note

Contrairement à Basic, la normalisation de chemin d'accès est effectuée avec Python dans la classe Session.


Classe Session Basic LibreOffice


        Option Explicit
        Option Compatible
        Option ClassModule
            
        Private _ps As Object ' Membre Privé
            
        Private Sub Class_Initialize()
            GlobalScope.BasicLibraries.LoadLibrary("Tools")
            Set _ps = CreateUnoService("com.sun.star.util.PathSubstitution")
        End Sub ' Constructeur
            
        Private Sub Class_Terminate()
            _ps = Nothing
        End Sub ' Destructeur
            
        Public Property Get SharedScripts() As String
            Dim inst As String, shr As String
            inst = ConvertFromURL(_ps.getSubstituteVariableValue("$(prog)"))
            shr = Tools.Strings.ReplaceString(inst,"Share","program")
            SharedScripts = shr & GetPathSeparator() &"Scripts"
        End Property ' Session.sharedScripts
            
        Public Property Get SharedPythonScripts() As String
            sharedPythonScripts = sharedScripts() & GetPathSeparator() &"python"
        End Property ' Session.sharedPythonScripts
            
        Public Property Get UserName() As String ' Compte Utilisateur
            userName = _ps.getSubstituteVariableValue("$(username)")
        End Property ' Session.userName
            
        Public Property Get UserProfile() As String ' Chemin système du profil Utilisateur
            userProfile = ConvertFromURL(_ps.getSubstituteVariableValue("$(user)"))
        End Property ' Session.userProfile
            
        Public Property Get UserScripts() As String ' Chemin système des scripts utilisateur
            userScripts = userProfile() & GetPathSeparator() &"Scripts"
        End Property ' Session.userScripts
            
        Public Property Get UserPythonScripts() As String ' Chemin système des scripts  Python Utilisateur
            userPythonScripts = userScripts() & GetPathSeparator() &"python"
        End Property ' Session.userPythonScripts
    

Aidez-nous !