CGnPe‖Python_Session : Session class

Contents
Abxjz‖

# qBME3‖Getting Session Information

nmTjF‖Computing LibreOffice user profile and shared modules system file paths can be performed with Python or with Basic languages. BeanShell, Java, JavaScript and Python scripts locations can be derived from this information.

## gMnyC‖Examples:

m498C‖With Python shell.

>>> from <the_module> import Session

yziJv‖>>> print(Session.SharedPythonScripts()) # static method

ezhbr‖>>> print(Session().UserName) # object property

K4Cjj‖>>> input(Session().UserProfile) # object property

### CVdoK‖From Tools – Macros - Run Macro... menu.

            from <the_module> import Session

            def demo_session():
                import screen_io as ui
            6YodC‖    ui.MsgBox(Session.Share(),title='Installation Share')  # static method
            ZyzBD‖    ui.Print(Session.SharedPythonScripts())  # static method
            widAX‖    s = Session()  # instance creation
            nXmDt‖    ui.MsgBox(s.UserName,title='Hello')  # object property
            q96Sj‖    ui.Print(s.UserPythonScripts)  # object property

            GAffb‖g_exportedScripts = (demo_session,)  # public macros

### GfLEb‖With LibreOffice Basic.

            Sub Session_example()
                Dim s As New Session ' instance of Session class
            LeCgt‖    Print "Shared scripts location:", s.SharedScripts
            bVkwR‖    MsgBox s.UserName,,"Hello"
                Print s.UserScripts, Chr(13), s.UserPythonScripts
            End Sub ' Session_example

### Dvp2n‖Using COM/OLE and Visual Basic Scripting language.

            u2czW‖' The service manager is always the entry point
            BiCRF‖' If there is no office running then an office is started up
            Set sm = WScript.CreateObject("com.sun.star.ServiceManager")
            mepxA‖' PathSubstitution service exhibits information to infer
            njK5P‖' <UserProfile|Share>/Scripts/python locations from
            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"

## XPAGf‖Python Session class:

            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'])
            niQ7c‖    @property  # alternative to '$(username)' variable
                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"])

CBvZv‖Unlike Basic, pathname normalization is performed with Python inside Session class.

## 8zUvW‖LibreOffice Basic Session class:

            Option Explicit
            Option Compatible
            Option ClassModule

            ivAG6‖Private _ps As Object ' Private member

            Private Sub Class_Initialize()
                GlobalScope.BasicLibraries.LoadLibrary("Tools")
                Set _ps = CreateUnoService("com.sun.star.util.PathSubstitution")
            Q9sNs‖End Sub ' Constructor

            Private Sub Class_Terminate()
                _ps = Nothing
            ELSQJ‖End Sub ' Destructor

            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

            XeTjp‖Public Property Get UserName() As String ' User account name
                userName = _ps.getSubstituteVariableValue("$(username)")
            End Property ' Session.userName

            NsDBi‖Public Property Get UserProfile() As String ' User profile system path
                userProfile = ConvertFromURL(_ps.getSubstituteVariableValue("$(user)"))
            End Property ' Session.userProfile

            do2CY‖Public Property Get UserScripts() As String ' User scripts system path
                userScripts = userProfile() & GetPathSeparator() &"Scripts"
            End Property ' Session.userScripts

            Gg3yg‖Public Property Get UserPythonScripts() As String ' User Python scripts system path
                userPythonScripts = userScripts() & GetPathSeparator() &"python"
            End Property ' Session.userPythonScripts

Related Topics

Python Scripts Organization and Location

Importing Python Modules

Input/Output to Screen

Python programming examples

Please support us!