Получаване на информация за сесията

Системните файлови пътища на потребителския профил на Collabora Office и на споделените модули могат да се намерят както с 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,)  # публични макроси

С Collabora Office 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:

' Входната точка винаги е диспечерът на услугите
' Ако офис пакетът не е стартиран, се стартира
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"])
note

За разлика от Basic, в Python нормализирането на пътища се извършва в класа Session.


Класът Session на Collabora Office 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

Моля, подкрепете ни!