Получение информации о сеансе

Формирование системных путей к файлам профиля пользователя LibreOffice и общим модулям может быть реализовано на языке Python или Basic. На основе этой информации можно определить расположение сценариев BeanShell, Java, JavaScript и Python.

Примеры:

С помощью Python.

>>> from <the_module> import Session

>>> print(Session.SharedPythonScripts()) # статический метод

>>> print(Session().UserName) # свойство объекта

>>> input(Session().UserProfile) # свойство объекта

Из меню Сервис – Макросы - Выполнить макрос….


        from <the_module> import Session
            
        def demo_session():
            import screen_io as ui
            ui.MsgBox(Session.Share(),title='Installation Share')  # статический метод
            ui.Print(Session.SharedPythonScripts())  # статический метод
            s = Session()  # создание экземпляра
            ui.MsgBox(s.UserName,title='Hello')  # свойство объекта
            ui.Print(s.UserPythonScripts)  # свойство объекта
            
        g_exportedScripts = (demo_session,)  # публичные макросы
    

С помощью LibreOffice Basic.


        Sub Session_example()
            Dim s As New Session ' instance of Session class
            Print "Расположение общих сценариев:", s.SharedScripts
            MsgBox s.UserName,,"Привет!"
            Print s.UserScripts, Chr(13), s.UserPythonScripts
        End Sub ' Session_example
    

С помощью COM/OLE и языка Visual Basic Scripting language.


        ' Менеджер служб всегда служит точкой входа
        ' Если офис ещё не запущен, то он запускается автоматически
        Set sm = WScript.CreateObject("com.sun.star.ServiceManager")
        ' Служба PathSubstitution предоставляет данные для определения
        ' расположения <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"
    

Класс 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  # аналог для переменной '$(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"])
    
Значок примечания

В отличие от Basic, в Python нормализация пути выполняется внутри класса Session.


Класс Session (LibreOffice Basic):


        Option Explicit
        Option Compatible
        Option ClassModule
            
        Private _ps As Object ' Закрытая переменная класса
            
        Private Sub Class_Initialize()
            GlobalScope.BasicLibraries.LoadLibrary("Tools")
            Set _ps = CreateUnoService("com.sun.star.util.PathSubstitution")
        End Sub ' Конструктор
            
        Private Sub Class_Terminate()
            _ps = Nothing
        End Sub ' Деструктор
            
        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 ' Имя учётной записи пользователя
            userName = _ps.getSubstituteVariableValue("$(username)")
        End Property ' Session.userName
            
        Public Property Get UserProfile() As String ' Системный путь к профилю пользователя
            userProfile = ConvertFromURL(_ps.getSubstituteVariableValue("$(user)"))
        End Property ' Session.userProfile
            
        Public Property Get UserScripts() As String ' Системный путь к сценариям пользователя
            userScripts = userProfile() & GetPathSeparator() &"Scripts"
        End Property ' Session.userScripts
            
        Public Property Get UserPythonScripts() As String ' Системный путь к сценариям Python пользователя
            userPythonScripts = userScripts() & GetPathSeparator() &"python"
        End Property ' Session.userPythonScripts
    
Пожалуйста, поддержите нас!

Пожалуйста, поддержите нас!