# Run python macro from command line on a given file

I have a file hello.odt. I'd like to run a Python macro from the command line and have access to hello.odt from within the macro.

I've tried:

soffice hello.odt 'vnd.sun.star.script:myscript.py\$Hello?language=Python&location=share'


This is my python script:

import sys

def Hello(*args):

# get the doc from the scripting context which is made available to all scripts
desktop = XSCRIPTCONTEXT.getDesktop()
model = desktop.getCurrentComponent()

# the print statement is here only for debugging purposes
# "model" should be the currently opened document
print(model)

# then do stuff with the document...


The script doesn't seem to see "model" and prints "None". My ultimate goal is to generate the table of contents by invoking ".uno:UpdateAllIndexes". But first I need access the document. That's why i'm printing out "model".

This answer suggests opening the file, then wait 3 seconds for office to launch, then run the macro. But I find it odd.

edit retag close merge delete

Sort by » oldest newest most voted

The answer cited in your question talks about external python macros, run from shell - so they should actually synchronize their execution with LO (unlike what you seem to do: macros will only run inside LO when it already started). I suppose that you would still need something like macro:///to prepend your macro (see https://bugs.documentfoundation.org/s...). However, I didn't test this myself with python.

more

Thanks for your answer. I had a look at the bugreport. I think I need clarification on the macro full url syntax: Sometimes I see double slash: macro://path.to.macro, sometimes I see triple slash: macro:///path.to.macro what's the difference? Also, what about the vnd.sun.star.script: prefix? Do I need to include it? like this: macro://vnd.sun.star.script:myscript.py Note: I placed myscript.py in /Applications/LibreOffice.app/Contents/Resources/Scripts/python/ Thanks

( 2017-02-07 09:21:43 +0200 )edit

Please see comment 4 there for some information; unfortunately I cannot say more.

( 2017-02-07 09:43:56 +0200 )edit

## Stats

Asked: 2017-02-07 00:39:28 +0200

Seen: 382 times

Last updated: Feb 07 '17