| Server IP : 121.121.20.254 / Your IP : 216.73.216.182 Web Server : Microsoft-IIS/10.0 System : Windows NT WEB-SERVER 10.0 build 20348 (Windows Server 2022) AMD64 User : IUSR ( 0) PHP Version : 8.3.28 Disable Function : NONE MySQL : ON | cURL : ON | WGET : OFF | Perl : OFF | Python : OFF | Sudo : OFF | Pkexec : OFF Directory : /Program Files/LibreOffice/help/en-US/text/sbasic/python/ |
Upload File : |
<!DOCTYPE html>
<html lang="en-US" dir="ltr">
<head>
<base href="../../../../">
<noscript><meta http-equiv="refresh" content="0; URL=../../../../en-US/noscript.html"></noscript>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Python : Importing Modules</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="en-US/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="en-US/bookmarks.js" defer></script><script type="text/javascript" src="en-US/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="en-US/text/shared/05/new_help.html"><div></div></a><a class="logo" href="en-US/text/shared/05/new_help.html"><p dir="auto">LibreOffice 24.2 Help</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">Module</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">Contents</label><div id="Contents" class="contents-treeview"></div></aside><div id="SearchFrame"><div id="Bookmarks">
<input id="search-bar" type="search" class="search" placeholder="Search in bookmarks for chosen module" 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">
<a name="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 name="pythonimporth1"></a>Importing Python Modules</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="en-US/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 name="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="en-US/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">User or Shared Modules</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="en-US/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="Click on text to copy to clipboard"><pre dir="auto"><code class="language-python line-numbers">
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
user_lib = Session().UserPythonScripts # User scripts location
if not user_lib in sys.path:
sys.path.insert(0, user_lib) # Add to search path
import screen_io as ui # 'screen_io.py' module resides in user_lib directory
# Your code follows here
</code></pre></div>
<p id="N0478" class="paragraph" dir="auto">This Python example exposes a local XSCRIPTCONTEXT variable to an imported module:</p>
<div class="pycode" itemscope="true" itemtype="http://schema.org/SoftwareSourceCode" itemprop="codeSampleType" content="snippet" data-tooltip="Click on text to copy to clipboard"><pre dir="auto"><code class="language-python line-numbers">
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import uno, sys
share_lib = Session.SharedPythonScripts() # Shared scripts location
if not share_lib in sys.path:
sys.path.insert(0, share_lib) # Add to search path
from IDE_utils import ScriptContext # 'IDE_utils.py' sits with shared Python scripts.
XSCRIPTCONTEXT = ScriptContext(uno.getComponentContext)
# Your code follows here
</code></pre></div>
<h3 id="N0489" dir="auto">Installation Modules for Applications</h3>
<p id="N0490" class="paragraph" dir="auto">Unlike personal and shared scripts, LibreOffice installation scripts can be imported any time. Next to <span class="literal">uno</span> & <span class="literal">unohelper</span> LibreOffice Python modules, other scripts present in <span class="literal"><installation_path>/program</span> directory can be imported directly, such as the <span class="literal">msgbox</span> module.</p>
<p id="N0491" class="paragraph" dir="auto">With Python shell:</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="en-US/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="Click on text to copy to clipboard"><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
# Note: imported modules remain loaded in this example.
class PythonLibraries():
""" Python library loader and module importer
adapted from 'Bibliothèque de fonctions' by Hubert Lambert
at https://forum.openoffice.org/fr/forum/viewtopic.php?p=286213 """
def isImportedModule(module_name: str) -> bool:
""" Check run time module list """
return (module_name in sys.modules.keys())
def isLoadedLibrary(lib_name: str) -> bool:
""" Check PYTHON_PATH content """
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):
""" remove directory from PYTHON_PATH """
sys.path.remove(lib_name)
g_exportedScripts = (OnDocPostOpenLoadPython, OnDocQueryCloseUnloadPython)
</code></pre></div>
<a name="relatedtopics"></a><div class="relatedtopics">
<p class="related" itemprop="mentions" dir="auto"><a name="related"></a><span class="emph">Related Topics</span>
</p>
<div class="relatedbody" itemprop="mentions">
<div class="embedded"><p class="embedded" dir="auto"><a target="_top" href="en-US/text/sbasic/python/python_session.html">Getting Session Information</a></p></div>
<div class="embedded"><p class="embedded" dir="auto"><a target="_top" href="en-US/text/sbasic/python/python_programming.html">Programming with Python Scripts</a></p></div>
<div class="embedded"><p class="embedded" dir="auto"><a target="_top" href="en-US/text/sbasic/python/python_locations.html">Python Scripts Organization and Location</a></p></div>
<p id="N0580" class="paragraph" dir="auto">
Refer to <a target="_top" href="en-US/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><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 : Importing Modules</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>