Difference between revisions of "FR/Documentation/Python/Python as a macro language"

From Apache OpenOffice Wiki
Jump to: navigation, search
Line 24: Line 24:
 
===Dossier partagé de OpenOffice===
 
===Dossier partagé de OpenOffice===
  
Scripts that shall be shared throughout all users of a concrete OpenOffice.org installation can be stored with the share directory. All default scripts coming with OpenOffice.org are located here. In general, this directory should not be used for script deployment (see later uno-packages).  
+
Les scripts qui seront partagés entre tous les utilisateurs d'une installation concrète d'OpenOffice.org peuvent être stockés dans ce répertoire de partage. Tous les scripts par défaut venant avec OpenOffice.org sont situés ici. En général, ce répertoire ne doit pas être utilisé pour le déploiement de scripts (voir plus loin les uno-packages).
 
+
Les fichiers de script sont simplement stockés dans le système de fichiers. L'emplacement du répertoire (comme les répertoires d'utilisateurs) dépend de la version d'OpenOffice.org utilisée et du système d'exploitation. Quelques exemples :
The script files are simply stored within the file system. The directory location is (like the user directories) depending on the used OpenOffice.org version and the operating system. Some examplaes are:
+
 
+
 
====OpenOffice 2.x====
 
====OpenOffice 2.x====
 
* windows '''C:\Program Files\OpenOffice.org 2.0\share\Scripts\python'''
 
* windows '''C:\Program Files\OpenOffice.org 2.0\share\Scripts\python'''
Line 33: Line 31:
  
 
====OpenOffice 3.x====
 
====OpenOffice 3.x====
* windows 7/64Bit ''C:\Program Files (x86)\OpenOffice.org 3\Basis\share\Scripts\python'''
+
* windows 7/32Bit ''C:\Program Files (x86)\OpenOffice.org 3\Basis\share\Scripts\python'''
 
* ubuntu 10.04 '''/usr/lib/openoffice/basis3.2/share/Scripts/python'''
 
* ubuntu 10.04 '''/usr/lib/openoffice/basis3.2/share/Scripts/python'''
  
===Embedded within an OpenOffice.org's document===
+
====OpenOffice 4.x====
 +
* windows 7/64Bit ''C:\Program Files (x86)\OpenOffice.org 4\share\Scripts\python'''
 +
* ubuntu 10.04 ???
 +
 
 +
===Inclus dans un document OpenOffice===
  
An OpenOffice.org document is a zip-File, which contains different files. Python scripts within documents are stored in Scripts/python subdirectory.  
+
Un document OpenOffice.org est un fichier zip, qui contient différents fichiers. Les scripts Python dans les documents sont stockés dans le sous-répertoire Scripts / python.
  
If you want to ship your self written python scripts within a document, you should first develop your scripts in the (above mentioned) user directory and then finally move the scripts into the document with your favorite zip tool. However, note that you must reassign every binding you did before to the script instances in the document. Ideally, you move away the scripts from the user directory and do a regression test on the document's functionality.
+
Si vous souhaitez expédier vos scripts personnels en python dans un document, vous devez d'abord développer vos scripts dans le répertoire utilisateur (mentionné ci-dessus), puis enfin déplacer les scripts dans le document avec votre outil préféré zip. Toutefois, notez que vous devez réaffecter toutes les liaisons que vous avez déjà effectuées aux instances de script dans le document. Idéalement, vous écartez les scripts du répertoire utilisateur et effectuez un test de régression sur la fonctionnalité du document.
 +
Vous pouvez aussi utiliser l'extension [https://forum.openoffice.org/fr/forum/viewtopic.php?f=18&t=52834 An Other cript Organizer].
  
After moving the script files into the document, you have to add some lines (boldly printed) to the ''META-INF/manifest.xml'' file:
+
Après avoir déplacé les fichiers de script dans le document, vous devez ajouter quelques lignes (mises en évidence) au fichier '' META-INF / manifest.xml '':<source lang=xml>
<source lang=xml>
+
 
<?xml version="1.0" encoding="UTF-8"?>
 
<?xml version="1.0" encoding="UTF-8"?>
 
<!DOCTYPE manifest:manifest PUBLIC "-//OpenOffice.org//DTD Manifest 1.0//EN" "Manifest.dtd">
 
<!DOCTYPE manifest:manifest PUBLIC "-//OpenOffice.org//DTD Manifest 1.0//EN" "Manifest.dtd">
Line 56: Line 58:
 
  <manifest:file-entry manifest:media-type="" manifest:full-path="Thumbnails/"/>
 
  <manifest:file-entry manifest:media-type="" manifest:full-path="Thumbnails/"/>
 
  <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="settings.xml"/>
 
  <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="settings.xml"/>
  <manifest:file-entry manifest:media-type="" manifest:full-path="Scripts/python/push_me.py"/>
+
  '''<manifest:file-entry manifest:media-type="" manifest:full-path="Scripts/python/push_me.py"/>
 
  <manifest:file-entry manifest:media-type="application/binary" manifest:full-path="Scripts/python/"/>
 
  <manifest:file-entry manifest:media-type="application/binary" manifest:full-path="Scripts/python/"/>
 
  <manifest:file-entry manifest:media-type="application/binary" manifest:full-path="Scripts/"/>
 
  <manifest:file-entry manifest:media-type="application/binary" manifest:full-path="Scripts/"/>
</manifest:manifest>
+
'''</manifest:manifest>
 
</source>
 
</source>
 
When you open the document afterwards, the OpenOffice.org's UI should warn you about script content within the document (when this is not the case, you either have switched off the warning in the options or you did something wrong).
 
When you open the document afterwards, the OpenOffice.org's UI should warn you about script content within the document (when this is not the case, you either have switched off the warning in the options or you did something wrong).

Revision as of 17:14, 10 December 2016

Pyuno prend en charge le framework de script OpenOffice livré avec OpenOffice 4.1.3. Le support actuel est limité au cadre principal ( core framework ), ce qui signifie que l'exécution et l'affectation des macros via la boîte de dialogue standard Tools / Macro fonctionne correctement, mais l'édition et le débogage des macros ne sont pas intégrés dans l'interface utilisateur OpenOffice.org (Simplemenr en raison du manque de ressources pour le développement). Utilisez votre éditeur de texte favori pour créer et modifier des scripts python.

Emplacement des scripts

Scripts to be excuted in OpenOffice.org can be stored within the following locations: LocalisationScriptsPython.jpg

Répertoire utilisateur de OpenOffice

C'est l'endroit standard pour les scripts personnels en python. Les fichiers de script sont simplement stockés dans le système de fichiers. L'emplacement du répertoire dépend de la version utilisée d'OpenOffice et du système d'exploitation. Certains exemples sont:

OpenOffice 2.x

  • windows - C:\Documents and Settings\<current-user\>Application Data\OpenOffice.org 2.0\user\Scripts\python
  • unix - ~/.openoffice.org.2.0/user/Scripts/python, ~/.openoffice.org.2.0/user/Scripts/python

OpenOffice 3.x

  • windows 7 - C:\Users\<current-user>\AppData\Roaming\OpenOffice.org\3\user\Scripts\python
  • unix - ~/.openoffice.org/3/user/Scripts/python

OpenOffice 4.x

  • windows 7 - C:\Users\<current-user>\AppData\Roaming\OpenOffice.org\4\user\Scripts\python
  • unix - ~/.openoffice.org/4/user/Scripts/python

Notez que le dernier sous-répertoire python peut avoir besoin d'être créé initialement. Assurez-vous que "python" est entièrement écrit en minuscules. Vous pouvez ajouter des sous-répertoires arbitrairement imbriqués, les noms de ces répertoires sont reflétés dans l'interface utilisateur.

Exemple: le ficher dynamicDialog.py peut simplement être placé dans le répertoire ci-dessus. Ensuite, ouvrez la boîte de dialogue Outils / Macros / Exécuter macro et naviguez jusqu'à la position affichée dans l'image ci-dessus. Cliquez sur Exécuter pour exécuter le script python, qui ouvre une autre boîte de dialogue avec un bouton poussoir et un champ d'étiquette. Cliquez sur le bouton pour augmenter le nombre dans le champ de l'étiquette. La boîte de dialogue peut être fermée en appuyant sur ESC.

Dossier partagé de OpenOffice

Les scripts qui seront partagés entre tous les utilisateurs d'une installation concrète d'OpenOffice.org peuvent être stockés dans ce répertoire de partage. Tous les scripts par défaut venant avec OpenOffice.org sont situés ici. En général, ce répertoire ne doit pas être utilisé pour le déploiement de scripts (voir plus loin les uno-packages). Les fichiers de script sont simplement stockés dans le système de fichiers. L'emplacement du répertoire (comme les répertoires d'utilisateurs) dépend de la version d'OpenOffice.org utilisée et du système d'exploitation. Quelques exemples :

OpenOffice 2.x

  • windows C:\Program Files\OpenOffice.org 2.0\share\Scripts\python
  • unix /usr/lib/openoffice/share/Scripts/python

OpenOffice 3.x

  • windows 7/32Bit C:\Program Files (x86)\OpenOffice.org 3\Basis\share\Scripts\python'
  • ubuntu 10.04 /usr/lib/openoffice/basis3.2/share/Scripts/python

OpenOffice 4.x

  • windows 7/64Bit C:\Program Files (x86)\OpenOffice.org 4\share\Scripts\python'
  • ubuntu 10.04 ???

Inclus dans un document OpenOffice

Un document OpenOffice.org est un fichier zip, qui contient différents fichiers. Les scripts Python dans les documents sont stockés dans le sous-répertoire Scripts / python.

Si vous souhaitez expédier vos scripts personnels en python dans un document, vous devez d'abord développer vos scripts dans le répertoire utilisateur (mentionné ci-dessus), puis enfin déplacer les scripts dans le document avec votre outil préféré zip. Toutefois, notez que vous devez réaffecter toutes les liaisons que vous avez déjà effectuées aux instances de script dans le document. Idéalement, vous écartez les scripts du répertoire utilisateur et effectuez un test de régression sur la fonctionnalité du document. Vous pouvez aussi utiliser l'extension An Other cript Organizer.

Après avoir déplacé les fichiers de script dans le document, vous devez ajouter quelques lignes (mises en évidence) au fichier META-INF / manifest.xml :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE manifest:manifest PUBLIC "-//OpenOffice.org//DTD Manifest 1.0//EN" "Manifest.dtd">
<manifest:manifest xmlns:manifest="http://openoffice.org/2001/manifest">
 <manifest:file-entry manifest:media-type="application/vnd.oasis.opendocument.text" manifest:full-path="/"/>
 <manifest:file-entry manifest:media-type="application/vnd.sun.xml.ui.configuration" manifest:full-path="Configurations2/"/>
 <manifest:file-entry manifest:media-type="" manifest:full-path="Pictures/"/>
 <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="content.xml"/>
 <manifest:file-entry :media-type="text/xml" manifest:full-path="styles.xml"/>
 <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="meta.xml"/>
 <manifest:file-entry manifest:media-type="" manifest:full-path="Thumbnails/thumbnail.png"/>
 <manifest:file-entry manifest:media-type="" manifest:full-path="Thumbnails/"/>
 <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="settings.xml"/>
 '''<manifest:file-entry manifest:media-type="" manifest:full-path="Scripts/python/push_me.py"/>
 <manifest:file-entry manifest:media-type="application/binary" manifest:full-path="Scripts/python/"/>
 <manifest:file-entry manifest:media-type="application/binary" manifest:full-path="Scripts/"/>
'''</manifest:manifest>

When you open the document afterwards, the OpenOffice.org's UI should warn you about script content within the document (when this is not the case, you either have switched off the warning in the options or you did something wrong).

Example:To see how it works, download File:Push me python4.odt. The document contains a push button and a multi line edit control. Pressing the button adds a new line with the current time stamp to the multi line edit control.

Embedded within a uno-package in OpenOffice.org's user directory (read only)

Often, distributing scripts in documents is not what you want (for instance when you want to modify the application itself or you want to use the same scripts with multiple documents ). Therefor you can place your scripts simply within uno-packages.

A uno-package is a zip-file. Its name must end with .pkg, otherwise it does not work. file, where you must define the subdirectory (required!) that shall contain scripts. For instance the sample pyhello2.uno.pkg has the following file structure:

META-INF/
META-INF/manifest.xml
package/
package/hallo.py

The hallo.py contains the scripts. How to write scripts is explained below. However, in order to make a script work within a uno package, you must add some dummy code.

# ... here is the python script code
 
# this must be added to every script file (the
# name org.openoffice.script.DummyImplementationForPythonScripts should be changed to something
# different (must be unique within an office installation !)
# --- faked component, dummy to allow registration with unopkg, no functionality expected
import unohelper
g_ImplementationHelper = unohelper.ImplementationHelper()
g_ImplementationHelper.addImplementation( \
	None,"org.openoffice.script.DummyImplementationForPythonScripts", \
    ("org.openoffice.script.DummyServiceForPythonScripts",),)

By default, every .py-file is interpreted as a UNO component. Not having the above lines within the .py file would raise errors during deployment.

The directory name (here package) can be choosen freely. A uno-package with a python script must contain a META-INF/manifest.xml, which needs to point to the freely chosen directory name.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE manifest:manifest PUBLIC "-//OpenOffice.org//DTD Manifest 1.0//EN" "Manifest.dtd">
<manifest:manifest xmlns:manifest="http://openoffice.org/2001/manifest">
<manifest:file-entry manifest:media-type="application/vnd.sun.star.framework-script" manifest:full-path="package"/>
</manifest:manifest>

Every user can add packages via the package manager (Tools/Package manager). Note, that content within the package is by design readonly, it is really a pure deployment, not a development mechanism. This might be the reason, why scripts in packages cannot be viewed via Tools/Macros/Organize macros/Python dialog. Embedded within a uno-package in OpenOffice.org's share directory (read only)

Packages can be added by an administrator to a complete OpenOffice.org installation, so that every user can use run the macros located within the package. This can be done with the unopkg tool.

Script coding

A python script within the OpenOffice.org's scripting framework is a function (introduced by the def keyword) within a .py file. For execution via the Tools/Macros/Run macro dialog, the script must have an empty argument list. For typical event listeners, the function must have exactly one argument (the event). In general, the number of arguments depend on the context where the function shall be used. Currently, the .py file must use unix line feeds, this will be changed in future.

A single .py file may contain an arbitrary number of function definitions. By default, all function definitions are exported ( = shown in the macro selection dialog). As this may become tedious, exports can be limited to a smaller set of functions by having a global variable named g_exportedScripts, which is a tuple of function definitions.

At the current integration level, .py files can only import python modules which are within the python PYTHONPATH. By default this is just the python runtime with its standard libraries and the uno bridge files. This means that python macros cannot reference other python macro files. This limitation may be changed in future but exists currently. Python macros can, of course, import from any module you place in the PYTHONPATH; but you must do that yourself and the results will not be portable.

(a reader wonders: couldn't the pythonloader automatically append the OOo scripting dirs to PYTHONPATH?)

Before executing the source code within the module, the global variable XSCRIPTCONTEXT is inserted as global variable within the module (this variable also exists e.g. for javascript and beanshell, it is offered here for consistency reasons). It has three members (Document,Desktop and ComponentContext).

The comment of a function (introduced and ended by three ") is shown as description in the macros' selection dialog.

The compiled python script files are not added to sys.modules. There may exist multiple instances of the same module at the same time. Example:

 
# HelloWorld python script for the scripting framework
 
def HelloWorldPython( ):
    """Prints the string 'Hello World(in Python)' into the current document"""
    #get the doc from the scripting context which is made available to all scripts
    model = XSCRIPTCONTEXT.getDocument()
    text = model.Text
    cursor = text.createTextCursor()
    text.insertString( cursor, "Hello World(in Python)", 0 )

Error handling and debugging

Errors during compilation or execution of the scripts are passed as exceptions to the scripting framework where possible. The scripting framework in general opens a popup box and displays the message of the thrown exception.

However, sometimes this is not possible and an error gets silently ignored. The user realizes these errors, when

  • his python script file does not appear where it is expected to be
  • the name of the script file appears, but it does not contain any scripts
  • only part of the script gets executed.

You can get to know these problems by changing some flags in the OpenOffice.org 3/Basis/program/pythonscript.py file :

# Configuration ----------------------------------------------------
LogLevel.use = LogLevel.NONE                # alternavly use LogLevel.ERROR or LogLevel.DEBUG
LOG_STDOUT = False                          # True, writes to stdout
                                            # False, writes to user/Scripts/python/log.txt
ENABLE_EDIT_DIALOG=False                    # offers a minimal editor for editing.

Attaching a python debugger is currently not supported.

Credits

The python binding of the scripting framework is developed and maintained by Joerg Budischewski in his spare time. Many, many thanks to Tomas O'Connor from Sun for his great support and his code additions to the framework which made this binding possible. Please put low level questions about the binding to api@openoffice.apache.org.

Personal tools