Ayuda de LibreOffice 24.8
El servicio Session reúne varios métodos de uso general relativos a:
la instalación o el entorno de ejecución
Introspección de UNO
la invocación de secuencias de órdenes o programas externos
Antes de utilizar el servicio Session, es necesario cargar o importar la biblioteca ScriptForge:
    GlobalScope.BasicLibraries.LoadLibrary("ScriptForge")
    Dim session As Variant
    session = CreateScriptService("Session")
  
    from scriptforge import CreateScriptService
    session = CreateScriptService("Session")
  Below is a list of constants available to ease the designation of the library containing a Basic or Python script to invoke. Use them as session.CONSTANT.
| CONSTANT | Valor | ¿Dónde se encuentra la biblioteca? | Se aplica | 
|---|---|---|---|
| SCRIPTISEMBEDDED | "document" | en el documento | Basic + Python | 
| SCRIPTISAPPLICATION | "application" | en cualquier biblioteca compartida | Basic | 
| SCRIPTISPERSONAL | "user" | en Mis macros | Python | 
| SCRIPTISPERSOXT | "user:uno_packages" | en una extensión instalada para la cuenta de usuario actual | Python | 
| SCRIPTISSHARED | "share" | en Macros de la aplicación | Python | 
| SCRIPTISSHAROXT | "share:uno_packages" | en una extensión instalada para todos los usuarios | Python | 
| SCRIPTISOXT | "uno_packages" | en una extensión cuyos parámetros de instalación, empero, se desconocen | Python | 
| Lista de métodos en el servicio Session | ||
|---|---|---|
| 
             ExecuteBasicScript | 
             HasUnoProperty | |
Execute... methods in Session service behave as follows:      
Arguments are passed by value. Changes made by the called function to the arguments do not update their values in the calling script.      
A single value or an array of values is returned to the calling script.
Execute the BASIC script given its name and location, and fetch its result, if any.
If the script returns nothing, which is the case of procedures defined with Sub, the returned value is Empty.
session.ExecuteBasicScript(scope: str, script: str, args: any[0..*]): any
scope: String specifying where the script is stored. It can be either "document" (constant session.SCRIPTISEMBEDDED) or "application" (constant session.SCRIPTISAPPLICATION).
script: String specifying the script to be called in the format "library.module.method" as a case-sensitive string.
La biblioteca se carga en memoria si hace falta.
El módulo no debe ser de clases.
The method may be a Sub or a Function.
args: The arguments to be passed to the called script.
Consider the following Basic function named DummyFunction that is stored in "My Macros" in the "Standard" library inside a module named "Module1".
La función simplemente recibe dos valores enteros, v1 y v2, y devuelve la suma de todos los valores a partir de v1 y que terminan en v2.
    Function DummyFunction(v1 as Integer, v2 as Integer) As Long
        Dim result as Long, i as Integer
        For i = v1 To v2
            result = result + i
        Next i
        DummyFunction = result
    End Function
  The examples below show how to call DummyFunction from within Basic and Python scripts.
    Dim session : session = CreateScriptService("Session")
    Dim b_script as String, result as Long
    b_script = "Standard.Module1.DummyFunction"
    result = session.ExecuteBasicScript("application", b_script, 1, 10)
    MsgBox result ' 55
  
    session = CreateScriptService("Session")
    bas = CreateScriptService("Basic")
    b_script = 'Standard.Module1.DummyFunction'
    result = session.ExecuteBasicScript('application', b_script, 1, 10)
    bas.MsgBox(result) # 55
  Execute a Calc function using its English name and based on the given arguments.      
If the arguments are arrays, the function is executed as an array formula.
session.ExecuteCalcFunction(calcfunction: str, args: any[0..*]): any
calcfunction: The name of the Calc function to be called, in English.
args: The arguments to be passed to the called Calc function. Each argument must be either a string, a numeric value or an array of arrays combining those types.
    session.ExecuteCalcFunction("AVERAGE", 1, 5, 3, 7) ' 4
    session.ExecuteCalcFunction("ABS", Array(Array(-1, 2, 3), Array(4, -5, 6), Array(7, 8, -9)))(2)(2) ' 9
    session.ExecuteCalcFunction("LN", -3)
    ' Genera un error.
  
    session.ExecuteCalcFunction("AVERAGE", 1, 5, 3, 7) # 4
    session.ExecuteCalcFunction("ABS", ((-1, 2, 3), (4, -5, 6), (7, 8, -9)))[2][2] # 9
    session.ExecuteCalcFunction("LN", -3)
  Execute the Python script given its location and name, fetch its result if any. Result can be a single value or an array of values.
Si la secuencia de órdenes no se encuentra o no devuelve nada, el valor devuelto será Empty.
session.ExecutePythonScript(scope: str, script: str, args: any[0..*]): any
scope: One of the applicable constants listed above. The default value is session.SCRIPTISSHARED.
script: Either "library/module.py$method" or "module.py$method" or "myExtension.oxt|myScript|module.py$method" as a case-sensitive string.
library: The folder path to the Python module.
myScript: The folder containing the Python module.
module.py: The Python module.
method: The Python function.
args: The arguments to be passed to the called script.
Consider the Python function odd_integers defined below that creates a list with odd integer values between v1 and v2. Suppose this function is stored in a file named my_macros.py in your user scripts folder.
    def odd_integers(v1, v2):
        odd_list = [v for v in range(v1, v2 + 1) if v % 2 != 0]
        return odd_list
  Read the help page Python Scripts Organization and Location to learn more about where Python scripts can be stored.
The following examples show how to call the function odd_integers from within Basic and Python scripts.
    Dim script as String, session as Object
    script = "my_macros.py$odd_integers"
    session = CreateScriptService("Session")
    Dim result as Variant
    result = session.ExecutePythonScript(session.SCRIPTISPERSONAL, script, 1, 9)
    MsgBox SF_String.Represent(result)
  
    session = CreateScriptService("Session")
    script = "my_macros.py$odd_integers"
    result = session.ExecutePythonScript(session.SCRIPTISPERSONAL, script, 1, 9)
    bas.MsgBox(repr(result))
  Devuelve la configuración actual de exportación a PDF que se ha definido en el cuadro de diálogo , al cual se puede acceder al elegir .
Export options set with the dialog are kept for future use. Hence GetPDFExportOptions returns the settings currently defined. In addition, use SetPDFExportOptions to change current PDF export options.
This method returns a Dictionary object wherein each key represent export options and the corresponding values are the current PDF export settings.
Read the PDF Export wiki page to learn more about all available options.
session.GetPDFExportOptions(): obj
    Dim expSettings As Object, msg As String, key As String, optLabels As Variant
    expSettings = session.GetPDFExportOptions()
    optLabels = expSettings.Keys
    For Each key in optLabels
        msg = msg + key & ": " & expSettings.Item(key) & Chr(10)
    Next key
    MsgBox msg
    ' Zoom: 100
    ' Changes: 4
    ' Quality: 90
    ' ...
  Returns True if an UNO object contains the given method. Returns False when the method is not found or when an argument is invalid.
session.HasUnoMethod(unoobject: uno, methodname: str): bool
unoobject: el objeto que se inspeccionará.
methodname: the method as a case-sensitive string
    Dim a As Variant
    a = CreateUnoService("com.sun.star.sheet.FunctionAccess")
    MsgBox session.HasUnoMethod(a, "callFunction") ' True
  
    bas = CreateScriptService("Basic")
    a = bas.CreateUnoService("com.sun.star.sheet.FunctionAccess")
    result = session.HasUnoMethod(a, "callFunction")
    bas.MsgBox(result) # True
  Returns True if a UNO object has the given property. Returns False when the property is not found or when an argument is invalid.
session.HasUnoProperty(unoobject: uno, propertyname: str): bool
unoobject: el objeto que se inspeccionará.
propertyname: the property as a case-sensitive string
    Dim svc As Variant
    svc = CreateUnoService("com.sun.star.sheet.FunctionAccess")
    MsgBox session.HasUnoProperty(svc, "Wildcards")
  
    bas = CreateScriptService("Basic")
    a = bas.CreateUnoService("com.sun.star.sheet.FunctionAccess")
    result = session.HasUnoProperty(a, "Wildcards")
    bas.MsgBox(result) # True
  Abre un localizador uniforme de recursos (un URL, por sus siglas en inglés) en el navegador predeterminado.
session.OpenURLInBrowser(url: str)
url: el URL para abrir.
    ' Basic
    session.OpenURLInBrowser("help.libreoffice.org/")
  
    # Python
    session.OpenURLInBrowser("help.libreoffice.org/")
  Ejecuta una orden arbitraria del sistema y devuelve Verdadero si se inició con éxito.
session.RunApplication(command: str, parameters: str): bool
command: The command to execute. This may be an executable file or a document which is registered with an application so that the system knows what application to launch for that document. The command must be expressed in the current SF_FileSystem.FileNaming notation.
parameters: A list of space separated parameters as a single string. The method does not validate the given parameters, but only passes them to the specified command.
    session.RunApplication("Notepad.exe")
    session.RunApplication("C:\myFolder\myDocument.odt")
    session.RunApplication("kate", "/home/user/install.txt") ' GNU/Linux
  
    session.RunApplication("Notepad.exe")
    session.RunApplication(r"C:\myFolder\myDocument.odt")
    session.RunApplication("kate", "/home/user/install.txt") # GNU/Linux
  Send a message - with optional attachments - to recipients from the user's mail client. The message may be edited by the user before sending or, alternatively, be sent immediately.
session.SendMail(recipient: str, cc: str = '', bcc: str = '', subject: str = '', body: str = '', filenames: str = '', editmessage: bool = True)
recipient: una dirección electrónica (el destinatario del campo «A»).
cc: una lista de direcciones de correo electrónico separadas por comas (los destinatarios «con copia»).
bcc: una lista de direcciones de correo electrónico separadas por comas (los destinatarios «con copia oculta»).
subject: la cabecera del mensaje.
body: el contenido del mensaje como un texto sin formato.
filenames: una lista de nombres de archivo separados por comas. Cada uno de los nombres de archivo debe respetar la notación de SF_FileSystem.FileNaming.
editmessage: When True (default), the message is edited before being sent.
    session.SendMail("someone@example.com" _
        , Cc := "b@other.fr, c@other.be" _
        , FileNames := "C:\myFile1.txt, C:\myFile2.txt")
  
    session.SendMail("someone@example.com",
                     cc="john@other.fr, mary@other.be"
                     filenames=r"C:\myFile1.txt, C:\myFile2.txt")
  Modifies the PDF export settings defined in the dialog, which can be accessed by choosing .
Calling this method changes the actual values set in the dialog, which are used by the ExportAsPDF method from the Document service.
This method returns True when successful.
Read the PDF Export wiki page to learn more about all available options.
session.SetPDFExportOptions(pdfoptions: obj): bool
pdfoptions: Dictionary object that defines the PDF export settings to be changed. Each key-value pair represents an export option and the value that will be set in the dialog.
The following example changes the maximum image resolution to 150 dpi and exports the current document as a PDF file.
    Dim newSettings As Object, oDoc As Object
    Set oDoc = CreateScriptService("Document")
    Set newSettings = CreateScriptService("Dictionary")
    newSettings.Add("ReduceImageResolution", True)
    newSettings.Add("MaxImageResolution", 150)
    session.SetPDFExportOptions(newSettings)
    oDoc.ExportAsPDF("C:\Documents\myFile.pdf", Overwrite := True)
  Returns a list of the methods callable from an UNO object. The list is a zero-based array of strings and may be empty.
session.UnoMethods(unoobject: uno): str[0..*]
unoobject: el objeto que se inspeccionará.
    Dim svc : svc = CreateUnoService("com.sun.star.sheet.FunctionAccess")
    Dim methods : methods = session.UnoMethods(svc)
    Dim msg as String
    For Each m in methods
        msg = msg & m & Chr(13)
    Next m
    MsgBox msg
  
    bas = CreateScriptService("Basic")
    a = bas.CreateUnoService("com.sun.star.sheet.FunctionAccess")
    methods = session.UnoMethods(a)
    msg = "\n".join(methods)
    bas.MsgBox(msg)
  Returns a list of the properties of an UNO object. The list is a zero-based array of strings and may be empty.
session.UnoProperties(unoobject: uno): str[0..*]
unoobject: el objeto que se inspeccionará.
    Dim svc As Variant
    svc = CreateUnoService("com.sun.star.sheet.FunctionAccess")
    MsgBox SF_Array.Contains(session.UnoProperties(svc), "Wildcards") ' True
  
    bas = CreateScriptService("Basic")
    svc = bas.CreateUnoService("com.sun.star.sheet.FunctionAccess")
    properties = session.UnoProperties(a)
    b = "Wildcards" in properties
    bas.MsgBox(str(b)) # True
  Identify the type of a UNO object as a string.
session.UnoObjectType(unoobject: uno): str
unoobject: The object to identify.
    Dim svc As Variant, txt As String
    svc = CreateUnoService("com.sun.star.system.SystemShellExecute")
    txt = session.UnoObjectType(svc) ' "com.sun.star.comp.system.SystemShellExecute"
    svc = CreateUnoStruct("com.sun.star.beans.Property")
    txt = session.UnoObjectType(svc) ' "com.sun.star.beans.Property"
  
    bas = CreateScriptService("Basic")
    svc = bas.CreateUnoService("com.sun.star.system.SystemShellExecute")
    txt = session.UnoObjectType(svc) # "com.sun.star.comp.system.SystemShellExecute"
    svc = bas.CreateUnoService("com.sun.star.beans.Property")
    txt = session.UnoObjectType(svc) # "com.sun.star.beans.Property"
  Get some web content from a URI.
session.WebService(uri: str): str
uri: URI address of the web service.
    session.WebService("wiki.documentfoundation.org/api.php?" _
        & "hidebots=1&days=7&limit=50&action=feedrecentchanges&feedformat=rss")
  
    session.WebService(("wiki.documentfoundation.org/api.php?" 
                       "hidebots=1&days=7&limit=50&action=feedrecentchanges&feedformat=rss"))