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 '$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
    # 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.

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 However, I didn’t test this myself with python.

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://, sometimes I see triple slash: macro:/// what’s the difference? Also, what about the prefix? Do I need to include it? like this: macro:// Note: I placed in /Applications/ Thanks

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

working for me:

soffice "$name_of_maindef?language=Python&location=share"

run from C:\Program Files\LibreOffice\program>