<!DOCTYPE html>
<html lang="es" dir="ltr">
<head>
<base href="../../../../">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Python_Session: clase Session</title>
<link rel="shortcut icon" href="media/navigation/favicon.ico">
<link type="text/css" href="normalize.css" rel="Stylesheet">
<link type="text/css" href="prism.css" rel="Stylesheet">
<link type="text/css" href="default.css" rel="Stylesheet">
<script type="text/javascript" src="polyfills.js"></script><script type="text/javascript" src="languages.js"></script><script type="text/javascript" src="es/langnames.js"></script><script type="text/javascript" src="flexsearch.debug.js"></script><script type="text/javascript" src="prism.js"></script><script type="text/javascript" src="help2.js" defer></script><script type="text/javascript" src="a11y-toggle.js" defer></script><script type="text/javascript" src="paginathing.js" defer></script><script type="text/javascript" src="es/bookmarks.js" defer></script><script type="text/javascript" src="es/contents.js" defer></script><script type="text/javascript" src="help.js" defer></script><meta name="viewport" content="width=device-width,initial-scale=1">
</head>
<body>
<header id="TopLeftHeader"><a class="symbol" href="es/text/shared/05/new_help.html"><div></div></a><a class="logo" href="es/text/shared/05/new_help.html"><p dir="auto">Ayuda de LibreOffice 25.2</p></a><div class="dropdowns"><div class="modules">
<button type="button" data-a11y-toggle="modules-nav" id="modules" aria-haspopup="true" aria-expanded="false" aria-controls="modules-nav">Módulo</button><nav id="modules-nav" hidden=""></nav>
</div></div></header><aside class="leftside"><input id="accordion-1" name="accordion-menu" type="checkbox"><label for="accordion-1" dir="auto">Contenido</label><div id="Contents" class="contents-treeview"></div></aside><div id="SearchFrame"><div id="Bookmarks">
<input id="search-bar" type="search" class="search" placeholder="Buscar en los marcadores del módulo elegido" dir="auto"><div class="nav-container" tabindex="0"><nav class="index" dir="auto"></nav></div>
</div></div>
<div id="DisplayArea" itemprop="softwareHelp" itemscope="true" itemtype="http://schema.org/SoftwareApplication">
<noscript><div id="WarnJS"><h1 dir="auto">Active JavaScript en el navegador para mostrar las páginas de ayuda de LibreOffice.</h1></div></noscript>
<a id="N0339"></a> <meta itemprop="keywords" content="Session,UserName"> <meta itemprop="keywords" content="Session,SharedScripts"> <meta itemprop="keywords" content="Session,SharedPythonScripts"> <meta itemprop="keywords" content="Session,UserProfile"> <meta itemprop="keywords" content="Session,UserScripts"> <meta itemprop="keywords" content="Session,UserPythonScripts"> <meta itemprop="keywords" content="API,PathSubstitution">
<h1 id="N0340" dir="auto">
<a id="pythonsession"></a>Obtener información de la sesión</h1>
<p id="N0341" class="paragraph" dir="auto">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.</p>
<h2 id="N0343" dir="auto">Ejemplos:</h2>
<p id="N0344" class="paragraph" dir="auto">Con el intérprete de Python</p>
<p id="N0345" class="paragraph" dir="auto"><span class="literal">>>> from <the_module> import Session</span></p>
<p id="N0346" class="paragraph" dir="auto"><span class="literal">>>> print(Session.SharedPythonScripts()) # método estático</span></p>
<p id="N0347" class="paragraph" dir="auto"><span class="literal">>>> print(Session().UserName) # propiedad de objeto</span></p>
<p id="N0348" class="paragraph" dir="auto"><span class="literal">>>> input(Session().UserProfile) # propiedad de objeto</span></p>
<h3 id="N0349" dir="auto">Desde el menú <span class="menuitem">Herramientas ▸ Macros ▸ Ejecutar macro</span>.</h3>
<div class="pycode" itemscope="true" itemtype="http://schema.org/SoftwareSourceCode" itemprop="codeSampleType" content="snippet" data-tooltip="Pulse en el texto para copiarlo en el portapapeles"><pre dir="auto"><code class="language-python line-numbers">
from <the_module> import Session
def demo_session():
import screen_io as ui
ui.MsgBox(Session.Share(),title='Installation Share') # static method
ui.Print(Session.SharedPythonScripts()) # static method
s = Session() # creación de instancia
ui.MsgBox(s.UserName,title='Hola') # propiedad de objeto
ui.Print(s.UserPythonScripts) # propiedad de objeto
g_exportedScripts = (demo_session,) # macros públicas
</code></pre></div>
<h3 id="N0361" dir="auto">Con LibreOffice Basic</h3>
<div class="bascode" itemscope="true" itemtype="http://schema.org/SoftwareSourceCode" itemprop="codeSampleType" content="snippet" data-tooltip="Pulse en el texto para copiarlo en el portapapeles"><pre dir="auto"><code class="language-visual-basic line-numbers">
Sub Session_example()
Dim s As New Session ' instance of Session class
Print "Ubicación de secuencias compartidas:", s.SharedScripts
MsgBox s.UserName,,"Hola"
Print s.UserScripts, Chr(13), s.UserPythonScripts
End Sub ' Session_example
</code></pre></div>
<h3 id="N0368" dir="auto">Mediante COM/OLE y el lenguaje VBScript</h3>
<div class="bascode" itemscope="true" itemtype="http://schema.org/SoftwareSourceCode" itemprop="codeSampleType" content="snippet" data-tooltip="Pulse en el texto para copiarlo en el portapapeles"><pre dir="auto"><code class="language-visual-basic line-numbers">
' El gestor de servicios es siempre el punto de entrada
' Si no hay ninguna instancia en funcionamiento, se pone en marcha una.
Set sm = WScript.CreateObject("com.sun.star.ServiceManager")
' El servicio PathSubstitution muestra información para inferir
' <UserProfile|Share>/Scripts/python ubicaciones desde
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"
</code></pre></div>
<h2 id="N0381" dir="auto">Clase Session de Python:</h2>
<div class="pycode" itemscope="true" itemtype="http://schema.org/SoftwareSourceCode" itemprop="codeSampleType" content="snippet" data-tooltip="Pulse en el texto para copiarlo en el portapapeles"><pre dir="auto"><code class="language-python line-numbers">
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 # alternativa a la variable «$(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"])
</code></pre></div>
<div class="note">
<div class="noteicon" dir="auto"><img src="media/icon-themes/res/helpimg/note.svg" alt="note" style="width:40px;height:40px;"></div>
<div class="notetext"><p id="N0342" dir="auto">A diferencia de Basic, la normalización de nombres de rutas de acceso se realiza con Python en la clase Session.</p></div>
</div>
<br>
<h2 id="N0412" dir="auto">Clase Session de LibreOffice Basic:</h2>
<div class="bascode" itemscope="true" itemtype="http://schema.org/SoftwareSourceCode" itemprop="codeSampleType" content="snippet" data-tooltip="Pulse en el texto para copiarlo en el portapapeles"><pre dir="auto"><code class="language-visual-basic line-numbers">
Option Explicit
Option Compatible
Option ClassModule
Private _ps As Object ' miembro privado
Private Sub Class_Initialize()
GlobalScope.BasicLibraries.LoadLibrary("Tools")
Set _ps = CreateUnoService("com.sun.star.util.PathSubstitution")
End Sub ' constructor
Private Sub Class_Terminate()
_ps = Nothing
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
Public Property Get UserName() As String ' nombre de cuenta de usuario
userName = _ps.getSubstituteVariableValue("$(username)")
End Property ' Session.userName
Public Property Get UserProfile() As String ' ruta de perfil de usuario en el sistema
userProfile = ConvertFromURL(_ps.getSubstituteVariableValue("$(user)"))
End Property ' Session.userProfile
Public Property Get UserScripts() As String ' ruta de secuencias de órdenes de usuario en el sistema
userScripts = userProfile() & GetPathSeparator() &"Scripts"
End Property ' Session.userScripts
Public Property Get UserPythonScripts() As String ' ruta de secuencias de órdenes en Python de usuario en el sistema
userPythonScripts = userScripts() & GetPathSeparator() &"python"
End Property ' Session.userPythonScripts
</code></pre></div>
<a id="relatedtopics"></a><div class="relatedtopics">
<p class="related" itemprop="mentions" dir="auto"><a id="related"></a><span class="emph">Temas relacionados</span></p>
<div class="relatedbody" itemprop="mentions">
<div class="embedded"><p class="embedded" dir="auto"><a target="_top" href="es/text/sbasic/python/python_locations.html">Organización y ubicación de las macros en Python</a></p></div>
<div class="embedded"><p class="embedded" dir="auto"><a target="_top" href="es/text/sbasic/python/python_import.html">Importar módulos de Python</a></p></div>
<div class="embedded"><p class="embedded" dir="auto"><a target="_top" href="es/text/sbasic/python/python_screen.html">Entrada y salida de y hacia la pantalla</a></p></div>
<div class="embedded"><p class="embedded" dir="auto"><a target="_top" href="es/text/sbasic/python/python_examples.html">Ejemplos de programación en Python</a></p></div>
</div>
</div>
</div>
<div id="DonationFrame"></div>
<footer><h2 style="text-align: center;"><a href="https://books.libreoffice.org" target="_blank">Libros de LibreOffice</a></h2>
<div class="noteicon" dir="auto" style="display:flex;justify-content:center;flex-wrap:wrap;row-gap:15px;">
<img src="media/navigation/libo-writer.svg" alt="Writer Icon" style="width:60px;height:60px;"><img src="media/navigation/libo-calc.svg" alt="Calc Icon" style="width:60px;height:60px;"><img src="media/navigation/libo-impress.svg" alt="Impress Icon" style="width:60px;height:60px;"><img src="media/navigation/libo-draw.svg" alt="Draw Icon" style="width:60px;height:60px;"><img src="media/navigation/libo-base.svg" alt="Base Icon" style="width:60px;height:60px;"><img src="media/navigation/libo-math.svg" alt="Math Icon" style="width:60px;height:60px;"><img src="media/navigation/libo-symbol-black.svg" alt="Getting Started Icon" style="width:60px;height:60px;">
</div>
<div id="DEBUG" class="debug">
<h3 class="bug">Help content debug info:</h3>
<p dir="auto">This page is: <a href="https://opengrok.libreoffice.org/xref/help/source/text/sbasic/python/python_session.xhp" target="_blank">/text/sbasic/python/python_session.xhp</a></p>
<p dir="auto">Title is: Python_Session: clase Session</p>
<p id="bm_module" dir="auto"></p>
<p id="bm_system" dir="auto"></p>
<p id="bm_HID" dir="auto"></p>
</div></footer>
</body>
</html>