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.

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/show_bug.cgi?id=104441). 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://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

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

working for me:

soffice "vnd.sun.star.script:name_of_python_file.py$name_of_maindef?language=Python&location=share"

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