<!DOCTYPE html>
<html lang="es" dir="ltr">
<head>
<base href="../../../../">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Python: importación de módulos</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="N0461"></a> <meta itemprop="keywords" content="Python,import"> <meta itemprop="keywords" content="Python,Modules"> <meta itemprop="keywords" content="Python,pythonpath"> <meta itemprop="keywords" content="PythonLibraries">
<h1 id="N0462" dir="auto">
<a id="pythonimporth1"></a>Importar módulos de Python</h1>
<p id="N0463" class="paragraph" dir="auto">LibreOffice Python scripts come in three distinct flavors, they can be personal, shared or embedded in documents. They are stored in varying places described in <a target="_top" href="es/text/sbasic/python/python_locations.html">Python Scripts Organization and Location</a>. In order to import Python modules, their locations must be known from Python at run time.</p>
<p id="N0464" class="paragraph" dir="auto">This mechanism is illustrated for file system based modules and document based modules. Exception handling is omitted for clarity. The terms library or directory, scripts or modules are used interchangeably. A Python macro refers to a function inside a module.</p>
<div class="warning">
<div class="noteicon" dir="auto"><img src="media/icon-themes/res/helpimg/warning.svg" alt="warning" style="width:40px;height:40px;"></div>
<div class="notetext"><p id="N0465" dir="auto">Note that <span class="literal"><User Profile>/Scripts/python/pythonpath</span> local directory is always explored when running a Python macro from <span class="literal"><User Profile>/Scripts/python</span>.</p></div>
</div>
<br>
<h2 id="N0466" dir="auto">File System module import</h2>
<div class="embedded">
<a id="PythonFileSystemImport"></a>
<p id="N0241" class="paragraph" dir="auto">LibreOffice Basic libraries contain classes, routines and variables, Python modules contain classes, functions and variables. Common pieces of reusable Python or UNO features must be stored in <a target="_top" href="es/text/sbasic/python/python_locations.html">My macros</a> within <span class="literal">(User Profile)/Scripts/python/pythonpath</span>. Python libraries help organize modules in order to prevent module name collisions. Import <span class="literal">uno.py</span> inside shared modules.</p>
</div>
<h3 id="N0467" dir="auto">Módulos de usuario o compartidos</h3>
<p id="N0468" class="paragraph" dir="auto">Personal & shared Python scripts can be imported once their directories are included in Python run time path. Refer to <a target="_top" href="es/text/sbasic/python/python_session.html">Getting session information</a> page for more details regarding omitted Session Class.</p>
<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">
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
user_lib = Session().UserPythonScripts # Ubicación de las secuencias de órdenes del usuario
if not user_lib in sys.path:
sys.path.insert(0, user_lib) # Añadir a la ruta de búsqueda
import screen_io as ui # el módulo «screen_io.py» se encuentra en el directorio user_lib
# Su código comienza a partir de aquí
</code></pre></div>
<p id="N0478" class="paragraph" dir="auto">Este ejemplo de Python expone una variable local, XSCRIPTCONTEXT, a un módulo importado:</p>
<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">
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import uno, sys
share_lib = Session.SharedPythonScripts() # Ubicación de las secuencias compartidas
if not share_lib in sys.path:
sys.path.insert(0, share_lib) # Añadir a la ruta de búsqueda
from IDE_utils import ScriptContext # «IDE_utils.py» se encuentra en las secuencias de órdenes Python compartidas.
XSCRIPTCONTEXT = ScriptContext(uno.getComponentContext)
# Su código comienza a partir de aquí
</code></pre></div>
<h3 id="N0489" dir="auto">Módulos de instalación para aplicaciones</h3>
<p id="N0490" class="paragraph" dir="auto">A diferencia de las secuencias personales y compartidas, siempre es posible importar las secuencias instaladas por LibreOffice. Junto con los módulos Python <span class="literal">uno</span> y <span class="literal">unohelper</span> de LibreOffice, es posible importar otras secuencias que estén en el directorio <span class="literal"><ruta de la instalación>/program</span>, como es el caso del módulo <span class="literal">msgbox</span>.</p>
<p id="N0491" class="paragraph" dir="auto">Con el intérprete de Python:</p>
<p id="N0492" class="paragraph" dir="auto"><span class="literal">>>> import msgbox, uno</span></p>
<p id="N0494" class="paragraph" dir="auto"><span class="literal">>>> myBox = msgbox.MsgBox(uno.getComponentContext())</span></p>
<p id="N0495" class="paragraph" dir="auto"><span class="literal">>>> myBox.addButton("okay")</span></p>
<p id="N0496" class="paragraph" dir="auto"><span class="literal">>>> myBox.renderFromButtonSize()</span></p>
<p id="N0497" class="paragraph" dir="auto"><span class="literal">>>> myBox.numberOflines = 2</span></p>
<p id="N0499" class="paragraph" dir="auto"><span class="literal">>>> print(myBox.show("A small message",0,"Dialog title"))</span></p>
<h2 id="N0534" dir="auto">Document Module Import</h2>
<p id="N0535" class="paragraph" dir="auto">Importing a Python document embedded module is illustrated below. Error handling is not detailed. Python run time path is updated when document has been opened and before closure. Refer to <a target="_top" href="es/text/sbasic/shared/01040000.html">Event-Driven Macros</a> to learn how to associate Python macros to document events.</p>
<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">
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys, uno
def OnDocPostOpenLoadPython():
""" Prepare Python modules import when doc. loaded """
PythonLibraries.loadLibrary('lib/subdir') # Add directory to search path
PythonLibraries.loadLibrary('my_gui', 'screen_io') # Add dir. & import screen_io
def OnDocQueryCloseUnloadPython():
""" Cleanup PYTHON_PATH when doc. Gets closed """
PythonLibraries.unloadLibrary('my_gui') # Python runtime path cleanup
# Nota: los módulos importados permanecen cargados en este ejemplo.
class PythonLibraries():
""" Cargador de bibliotecas e importador de módulos para Python
adaptado de la «Bibliothèque de fonctions» de Hubert Lambert
en https://forum.openoffice.org/fr/forum/viewtopic.php?p=286213 """
def isImportedModule(module_name: str) -> bool:
""" Comprobar lista de módulos de tiempo de ejecución """
return (module_name in sys.modules.keys())
def isLoadedLibrary(lib_name: str) -> bool:
""" Comprobar contenido de PYTHON_PATH """
return (lib_name in sys.path)
def loadLibrary(lib_name: str, module_name=None):
""" add directory to PYTHON_PATH, import named module """
doc = XSCRIPTCONTEXT.getDocument()
url = uno.fileUrlToSystemPath(
'{}/{}'.format(doc.URL,'Scripts/python/'+lib_name)
if not url in sys.path:
sys.path.insert(0, url)
if module_name and not module_name in sys.modules.keys():
return zipimport.zipimporter(url).load_module(module_name)
def unloadLibrary(lib_name: str):
""" quitar el directorio de PYTHON_PATH """
sys.path.remove(lib_name)
g_exportedScripts = (OnDocPostOpenLoadPython, OnDocQueryCloseUnloadPython)
</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_session.html">Obtener información de la sesión</a></p></div>
<div class="embedded"><p class="embedded" dir="auto"><a target="_top" href="es/text/sbasic/python/python_programming.html">Programar con secuencias de órdenes en Python</a></p></div>
<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>
<p id="N0580" class="paragraph" dir="auto"> Refer to <a target="_top" href="es/text/sbasic/python/python_listener.html">Creating a Python Listener</a> for examples of event-driven macros.</p>
</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_import.xhp" target="_blank">/text/sbasic/python/python_import.xhp</a></p>
<p dir="auto">Title is: Python: importación de módulos</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>