Servicio ScriptForge.Basic

El servicio ScriptForge.Basic ofrece una colección de métodos de LibreOffice BASIC que ejecutar en un contexto Python. Los métodos del servicio Basic reproducen con exactitud la sintaxis y el comportamiento de las funciones incorporadas de BASIC.

Ejemplo típico:


   bas.MsgBox('Display this text in a message box from a Python script')
  
warning

El uso del servicio ScriptForge.Basic está limitado a las secuencias Python.


Invocación del servicio

note

Antes de utilizar el servicio Basic, importe el método CreateScriptService() del módulo scriptforge:



    from scriptforge import CreateScriptService
    bas = CreateScriptService("Basic")
  

Propiedades

Nombre

De solo lectura

Tipo

Descripción

MB_OK, MB_OKCANCEL, MB_RETRYCANCEL, MB_YESNO, MB_YESNOCANCEL

Integer

Valores: 0, 1, 5, 4, 3

MB_ICONEXCLAMATION, MB_ICONINFORMATION, MB_ICONQUESTION, MB_ICONSTOP

Integer

Valores: 48, 64, 32, 16

MB_ABORTRETRYIGNORE, MB_DEFBUTTON1, MB_DEFBUTTON2, MB_DEFBUTTON3

Integer

Valores: 2, 128, 256, 512

IDABORT, IDCANCEL, IDIGNORE, IDNO, IDOK, IDRETRY, IDYES

Integer

Valores: 3, 2, 5, 7, 1, 4, 6
Constantes que indican el botón seleccionado del MsgBox.

StarDesktop

Objeto
de UNO

Returns the StarDesktop object that represents the LibreOffice application.

ThisComponent

Objeto
de UNO

If the current component refers to a LibreOffice document, this method returns the UNO object representing the document. This property returns None when the current component does not correspond to a document.

ThisDatabaseDocument

Objeto
de UNO

If the script is being executed from a Base document or any of its subcomponents this method returns the main component of the Base instance. This property returns None otherwise.


Lista de métodos en el servicio Basic

CDate
CDateFromUnoDateTime
CDateToUnoDateTime
ConvertFromUrl
ConvertToUrl
CreateUnoService
CreateUnoStruct
DateAdd

DateDiff
DatePart
DateValue
Format
GetDefaultContext
GetGuiType
GetPathSeparator
GetSystemTicks

GlobalScope.BasicLibraries
GlobalScope.DialogLibraries
InputBox
MsgBox
Now
RGB
Xray


CDate

Converts a numeric expression or a string to a datetime.datetime Python native object.

note

This method exposes the Basic builtin function CDate to Python scripts.


Sintaxis:

svc.CDate(expression: any): obj

Parámetros:

expression: a numeric expression or a string representing a date.

Cuando se convierte una expresión de cadena, la fecha y la hora se debe introducir, ya sea como una de las pautas de aceptación de fechas definidas para su configuración regional (vea  ▸ Idiomas y regiones ▸ General) o en el formato de fechas de la ISO (por el momento, solo se acepta el formato con guiones: «2012-12-31», por ejemplo). En las expresiones numéricas, los valores a la izquierda del decimal representan la fecha, comenzando a partir del 31 de diciembre de 1899. Los valores a la derecha del decimal representan la hora.

Ejemplo:


    d = bas.CDate(1000.25)
    bas.MsgBox(str(d)) # 1902-09-26 06:00:00
    bas.MsgBox(d.year) # 1902
  

CDateFromUnoDateTime

Converts a UNO date/time representation to a datetime.datetime Python native object.

Sintaxis:

svc.CDateFromUnoDateTime(unodate: uno): obj

Parámetros:

unodate: A UNO date/time object of one of the following types: com.sun.star.util.DateTime, com.sun.star.util.Date or com.sun.star.util.Time

Ejemplo:

El ejemplo siguiente crea un objeto com.sun.star.util.DateTime y lo convierte en un objeto datetime.datetime de Python.


    uno_date = bas.CreateUnoStruct('com.sun.star.util.DateTime')
    uno_date.Year = 1983
    uno_date.Month = 2
    uno_date.Day = 23
    new_date = bas.CDateFromUnoDateTime(uno_date)
    bas.MsgBox(str(new_date)) # 1983-02-23 00:00:00
  

CDateToUnoDateTime

Converts a date representation into a com.sun.star.util.DateTime object.

Sintaxis:

svc.CDateToUnoDateTime(date: obj): uno

Parámetros:

date: A Python date/time object of one of the following types: datetime.datetime, datetime.date, datetime.time, float (time.time) or time.struct_time.

Ejemplo:


    from datetime import datetime
    current_datetime = datetime.now()
    uno_date = bas.CDateToUnoDateTime(current_datetime)
    bas.MsgBox(str(uno_date.Year) + "-" + str(uno_date.Month) + "-" + str(uno_date.Day))
  

ConvertFromUrl

Devuelve la ruta en la notación del sistema correspondiente a un URL file: dado.

Sintaxis:

svc.ConvertFromUrl(url: str): str

Parámetros:

url: un URL file: absoluto.

Valor de retorno:

A system path file name.

Ejemplo:


    filename = bas.ConvertFromUrl( "file:///C:/Program%20Files%20(x86)/LibreOffice/News.txt")
    bas.MsgBox(filename)
  

ConvertToUrl

Devuelve un URL file: para la ruta de sistema dada.

Sintaxis:

svc.ConvertToUrl(systempath: str): str

Parámetros:

systempath: una ruta de nombre de archivo en el formato del sistema, como una cadena.

Valor de retorno:

Un URL file: como cadena.

Ejemplo:


    url = bas.ConvertToUrl( 'C:\Program Files(x86)\LibreOffice\News.txt')
    bas.MsgBox(url)
  

CreateUnoService

Crea una instancia de un servicio de UNO mediante el ProcessServiceManager.

Sintaxis:

svc.CreateUnoService(servicename: str): uno

Parámetros:

servicename: A fully qualified service name such as com.sun.star.ui.dialogs.FilePicker or com.sun.star.sheet.FunctionAccess.

Ejemplo:


    dsk = bas.CreateUnoService('com.sun.star.frame.Desktop')
  

CreateUnoStruct

Returns an instance of a UNO structure of the specified type.

Sintaxis:

svc.CreateUnoStruct(unostructure: str): uno

Parámetros:

unostructure: A fully qualified structure name such as com.sun.star.beans.Property or com.sun.star.util.DateTime.

Ejemplo:


    date_struct = CreateUnoStruct('com.sun.star.util.DateTime')
  

DateAdd

Suma una fecha o un lapso de tiempo a una fecha u hora dada un cierto número de veces y devuelve la fecha resultante.

Sintaxis:

svc.DateAdd(interval: str, number: num, date: datetime): datetime

Parámetros:

interval: A string expression from the following table, specifying the date or time interval.

interval (string value)

Explicación

yyyy

Año

q

Trimestre

m

Mes

y

Día del año

w

Día de la semana

ww

Semana del año

d

Día

h

Hora

n

Minuto

s

Segundo


number: A numerical expression specifying how often the interval value will be added when positive or subtracted when negative.

date: A given datetime.datetime value, the interval value will be added number times to this datetime.datetime value.

Valor de retorno:

A datetime.datetime value.

Ejemplo:


    dt = datetime.datetime(2004, 1, 31)
    dt = bas.DateAdd("m", 1, dt)
    print(dt)
  

DateDiff

Returns the number of date or time intervals between two given date/time values.

Sintaxis:

svc.DateDiff(interval: str, date1: datetime, date2: datetime, firstdayofweek = 1, firstweekofyear = 1): int

Parámetros:

interval: A string expression specifying the date interval, as detailed in above DateAdd method.

date1, date2: The two datetime.datetime values to be compared.

firstdayofweek: An optional parameter that specifies the starting day of a week.

firstdayofweek value

Explicación

0

Utilizar valor predeterminado del sistema

1

Sunday (valor predeterminado)

2

Lunes

3

Martes

4

Miércoles

5

Jueves

6

Viernes

7

Sábado


firstweekofyear: An optional parameter that specifies the starting week of a year.

firstweekofyear value

Explicación

0

Utilizar valor predeterminado del sistema

1

Week 1 es la semana del día 1 de enero (predeterminado)

2

Week 1 es la primera semana que contiene cuatro o más días de ese año

3

Week 1 es la primera semana que únicamente contiene días del año nuevo


Valor de retorno:

Un número.

Ejemplo:


    date1 = datetime.datetime(2005,1, 1)
    date2 = datetime.datetime(2005,12,31)
    diffDays = bas.DateDiff('d', date1, date2)
    print(diffDays)
  

DatePart

The DatePart function returns a specified part of a date.

Sintaxis:

svc.DatePart(interval: str, date: datetime, firstdayofweek = 1, firstweekofyear = 1): int

Parámetros:

interval: A string expression specifying the date interval, as detailed in above DateAdd method.

date: The date/time from which the result is calculated.

firstdayofweek, firstweekofyear: optional parameters that respectively specify the starting day of a week and the starting week of a year, as detailed in above DateDiff method.

Valor de retorno:

The extracted part for the given date/time.

Ejemplo:


    print(bas.DatePart("ww", datetime.datetime(2005,12,31)
    print(bas.DatePart('q', datetime.datetime(1999,12,30)
  

DateValue

Calcula un dato de fecha a partir de una cadena de fecha.

Sintaxis:

svc.DateValue(date: str): datetime

Parámetros:

date: A string that contains the date that will be converted to a Date object.

note

La cadena pasada a DateValue debe expresarse en uno de los formatos de fecha definidos por su configuración regional (vea  ▸ Idiomas y regiones ▸ General) o en el formato «aaaa-mm-dd» (año, mes y día separados por guiones) de la ISO.


Valor de retorno:

La fecha calculada.

Ejemplo:


    dt = bas.DateValue("23-02-2011")
    print(dt)
  

Format

Converts a number to a string, and then formats it according to the format that you specify.

Sintaxis:

svc.Format(expression: any, format = ''): str

Parámetros:

expresión: la expresión numérica que quiere convertir en una cadena formateada.

formato: una cadena que especifica el código de formato para el número. Si se omite formato, la función Format funciona igual que la función Str() de LibreOffice BASIC.

Valor de retorno:

Cadena de texto.

Códigos de formato

La lista siguiente describe los códigos que puede utilizar para dar formato a una expresión numérica:

0: If expression has a digit at the position of the 0 in the format code, the digit is displayed, otherwise a zero is displayed.

If expression has fewer digits than the number of zeros in the format code, (on either side of the decimal), leading or trailing zeros are displayed. If the expression has more digits to the left of the decimal separator than the amount of zeros in the format code, the additional digits are displayed without formatting.

Decimal places in the expression are rounded according to the number of zeros that appear after the decimal separator in the format code.

#: si expresión contiene un dígito en la posición del sustitutivo # en el código formato, se muestra el dígito; de lo contrario, nada aparecerá en esta posición.

This symbol works like the 0, except that leading or trailing zeroes are not displayed if there are more # characters in the format code than digits in the expression. Only the relevant digits of the expression are displayed.

.: el sustitutivo para decimales determina el número de espacios decimales a la izquierda y a la derecha del separador decimal.

If the format code contains only # placeholders to the left of this symbol, numbers less than 1 begin with a decimal separator. To always display a leading zero with fractional numbers, use 0 as a placeholder for the first digit to the left of the decimal separator.

%: Multiplies the expressionby 100 and inserts the percent sign (%) where the expression appears in the format code.

E- E+ e- e+ : If the format code contains at least one digit placeholder (0 or #) to the right of the symbol E-, E+, e-, or e+, the expression is formatted in the scientific or exponential format. The letter E or e is inserted between the number and the exponent. The number of placeholders for digits to the right of the symbol determines the number of digits in the exponent.

Si el exponente es negativo, se muestra un signo menos justo antes de un exponente con E-, E+, e-, e+. Si el exponente es positivo, sólo se muestra un signo más antes de exponentes con E+ o e+.

The thousands delimiter is displayed if the format code contains the delimiter enclosed by digit placeholders (0 or #).

El uso de un punto como separador de miles y decimal depende del valor de configuración regional. El carácter real que se muestra como separador decimal depende del formato numérico de la configuración del sistema. Los ejemplos que se muestran aquí asumen que la configuración regional es "US".

- + $ ( ) space: A plus (+), minus (-), dollar ($), space, or brackets entered directly in the format code is displayed as a literal character.

Para que se muestren caracteres distintos de los que se indican aquí, es necesario colocarles una contrabarra (\) antes o entrecomillarlos (" ").

\ : The backslash displays the next character in the format code.

Characters in the format code that have a special meaning can only be displayed as literal characters if they are preceded by a backslash. The backslash itself is not displayed, unless you enter a double backslash (\\) in the format code.

Los caracteres que deben precederse por una barra oblicua inversa en el código de formato para que se muestren como caracteres literales son: caracteres de formato de hora y fecha (a, c, d, h, m, n, p, q, s, t, w, y, /, :), caracteres de formato numérico (#, 0, %, E, e, coma, punto) y caracteres de formato de cadena (@, &, <, >, !).

You can also use the following predefined number formats. Except for "General Number", all of the predefined format codes return the number as a decimal number with two decimal places.

Si se usan formatos predefinidos, el nombre del formato debe entrecomillarse.

Formatos predefinidos

General Number: los números se muestran tal como se han introducido.

Currency: inserta un signo de dólar delante del número y encierra los números negativos entre paréntesis.

Fixed: muestra al menos un dígito delante del separador decimal.

Standard: muestra números con un separador de millares.

Percent: multiplica el número por 100 y le añade un signo de porcentaje.

Scientific: muestra números en formato científico (por ejemplo, 1,00E+03 para 1000).

Un código de formato puede dividirse en tres secciones, separadas por punto y coma. La primera define el formato de los valores positivos; la segunda, el de los negativos; y la tercera se aplica al cero. Si solamente se especifica un código de formato, este se aplicará a todos los números.

Puede definir el formato regional de los números, las fechas y las monedas en LibreOffice BASIC al dirigirse a  ▸ Idiomas y regiones ▸ General. En los códigos de formato de BASIC, el punto decimal (.) se utiliza siempre como sustitutivo del separador decimal definido en la configuración regional elegida; este punto se reemplazará por el carácter correspondiente.

Lo mismo se aplica a los valores de configuración de los formatos de fecha, hora y moneda. El código de formato de Basic se interpretará y se mostrará según los valores de configuración del entorno local correspondientes.

Ejemplo:


    txt = bas.Format(6328.2, '##.##0.00')
    print(txt)
  

GetDefaultContext

Returns the default context of the process service factory, if existent, else returns a null reference.

GetDefaultContext is an alternative to the getComponentContext() method available from XSCRIPTCONTEXT global variable or from uno.py module.

Sintaxis:

svc.GetDefaultContext(): uno

Valor de retorno:

The default component context is used, when instantiating services via XMultiServiceFactory. See the Professional UNO chapter in the Developer's Guide on api.libreoffice.org for more information.

Ejemplo:


    ctx = bas.GetDefaultContext()
  

GetGuiType

Returns a numerical value that specifies the graphical user interface. This function is only provided for backward compatibility with previous versions.

Refer to system() method from platform Python module to identify the operating system.

Sintaxis:

svc.GetGuiType(): int

Ejemplo:


    n = bas.GetGuiType()
  

GetPathSeparator

Devuelve el separador de directorios, que depende del sistema operativo, utilizado para especificar las rutas de acceso de los archivos.

Use os.pathsep from os Python module to identify the path separator.

Sintaxis:

svc.GetPathSeparator(): str

Ejemplo:


    sep = bas.GetPathSeparator()
  

GetSystemTicks

Returns the number of system ticks provided by the operating system. You can use this function to optimize certain processes. Use this method to estimate time in milliseconds:

Sintaxis:

svc.GetSystemTicks(): int

Ejemplo:


    ticks_ini = bas.GetSystemTicks()
    time.sleep(1)
    ticks_end = bas.GetSystemTicks()
    bas.MsgBox("{} - {} = {}".format(ticks_end, ticks_ini,ticks_end - ticks_ini))
  

GlobalScope.BasicLibraries

Returns the UNO object containing all shared Basic libraries and modules.

This method is the Python equivalent to GlobalScope.BasicLibraries in Basic scripts.

Sintaxis:

svc.GlobalScope.BasicLibraries(): uno

Valor de retorno:

com.sun.star.script.XLibraryContainer

Ejemplo:

El ejemplo siguiente carga la biblioteca Gimmicks de BASIC si todavía no se ha cargado.


    libs = bas.GlobalScope.BasicLibraries()
    if not libs.isLibraryLoaded("Gimmicks"):
        libs.loadLibrary("Gimmicks")
  

GlobalScope.DialogLibraries

Devuelve el objeto UNO que contiene todas las bibliotecas compartidas de diálogos.

This method is the Python equivalent to GlobalScope.DialogLibraries in Basic scripts.

Sintaxis:

svc.GlobalScope.DialogLibraries(): uno

Valor de retorno:

com.sun.star.comp.sfx2.DialogLibraryContainer

Ejemplo:

The following example shows a message box with the names of all available dialog libraries.


    dlg_libs = bas.GlobalScope.DialogLibraries()
    lib_names = dlg_libs.getElementNames()
    bas.MsgBox("\n".join(lib_names))
  

InputBox

Sintaxis:

svc.InputBox(prompt: str, [title: str], [default: str], [xpostwips: int, ypostwips: int]): str

Parámetros:

prompt: String expression displayed as the message in the dialog box.

título: expresión de cadena que se muestra en la barra de título del cuadro de diálogo.

default: String expression displayed in the text box as default if no other input is given.

xpostwips: Integer expression that specifies the horizontal position of the dialog. The position is an absolute coordinate and does not refer to the window of LibreOffice.

ypostwips: Integer expression that specifies the vertical position of the dialog. The position is an absolute coordinate and does not refer to the window of LibreOffice.

If xpostwips and ypostwips are omitted, the dialog is centered on the screen. The position is specified in twips.

Valor de retorno:

String

Ejemplo:


    txt = s.InputBox('Introduzca una oración:', "Estimadx usuarix")
    s.MsgBox(txt, s.MB_ICONINFORMATION, "Confirmation of phrase")
  
note

For in-depth information please refer to Input/Output to Screen with Python on the Wiki.


MsgBox

Displays a dialog box containing a message and returns an optional value.
MB_xx constants help specify the dialog type, the number and type of buttons to display, plus the icon type. By adding their respective values they form bit patterns, that define the MsgBox dialog appearance.

Sintaxis:

bas.MsgBox(prompt: str, [buttons: int], [title: str])[: int]

Parámetros:

prompt: String expression displayed as a message in the dialog box. Line breaks can be inserted with Chr$(13).

title: String expression displayed in the title bar of the dialog. If omitted, the title bar displays the name of the respective application.

buttons: Any integer expression that specifies the dialog type, as well as the number and type of buttons to display, and the icon type. buttons represents a combination of bit patterns, that is, a combination of elements can be defined by adding their respective values:

Valor de retorno:

An optional integer as detailed in above IDxx properties.

Ejemplo:


    txt = s.InputBox('Introduzca una oración:', "Estimadx usuarix")
    s.MsgBox(txt, s.MB_ICONINFORMATION, "Confirmation of phrase")
  
note

For in-depth information please refer to Input/Output to Screen with Python on the Wiki.


Now

Returns the current system date and time as a datetime.datetime Python native object.

Sintaxis:

svc.Now(): datetime

Ejemplo:


    bas.MsgBox(bas.Now(), bas.MB_OK, "Now")
  

RGB

Returns an integer color value consisting of red, green, and blue components.

Sintaxis:

svc.RGB(red:int, green: int, blue: int): int

Parámetros:

red: Any integer expression that represents the red component (0-255) of the composite color.

green: Any integer expression that represents the green component (0-255) of the composite color.

blue: Any integer expression that represents the blue component (0-255) of the composite color.

The resulting Long value is calculated with the following formula:
Result = red×65536 + green×256 + blue.

warning

Under VBA compatibility mode (Option VBASupport 1), the Long value is calculated as
Result = red + green×256 + blue×65536
See RGB Function [VBA]


tip

The color picker dialog helps computing red, green and blue components of a composite color. Changing the color of text and selecting Custom color displays the color picker dialog.


Valor de retorno:

Integer

Ejemplo:


    YELLOW = bas.RGB(255,255,0)
  

Xray

Inspect Uno objects or variables.

Sintaxis:

svc.Xray(obj: any)

Parámetros:

obj: A variable or UNO object.

Ejemplo:


    bas.Xray(bas.StarDesktop)
  
warning

Todas las rutinas o identificadores BASIC de ScriptForge precedidas por guion bajo «_» están reservadas para uso interno. No deben utilizarse en macros BASIC o secuencias Python.


¡Necesitamos su ayuda!