How to properly execute a python script from within a calc macro shell?

I have a python script for testing purposes that just echos back the args. The file is echo_test.py located in my home directory and has this inside:

#!/bin/env python3

import sys

def main():
	print(" ".join(sys.argv[1:]))
	return 0

if __name__ == "__main__":
	sys.exit(main())

If I run the following 2 commands from a bash terminal I will get 2 files (echo.txt and echopy.txt) both with the word hello in them.

echo hello > echo.txt
echo_test.py hello > echopy.txt

Now in LibreCalc I have the following functions to test the command:

sub TestLinuxCommands

	ExeLinuxCommandSync("echo hello > echo.txt")
	ExeLinuxCommandSync("echo_test.py hello > echopy.txt")
	
end sub

Function ExeLinuxCommandSync(command as string) 

	'build shell command
	shellCommand = "-c '" & command & "'"
	
	'run command
	shellResponse = Shell ("bash", 0, shellCommand, true)
	
End Function

After running the TestLinuxCommands function, my home directory has both text files, but only the one using the system echo command has text in it. I cannot understand why there is a difference when running the python script from shell within a macro vs running directly from the terminal.

Any ideas?

Thanks,
John Vickers

If you need execute a return data from scripts, why not execute directly from Python?

subprocess.check_output()

better

subprocess.run() 

https://docs.python.org/3.5/library/subprocess.html#using-the-subprocess-module

The Python scripts I need to run are not controlled by me, I am only a consumer of their outputs. The only examples I have found to use subprocess from within calc involve unzipping the ods file and rezipping with python scripts embedded. I really don’t like that method because the next person that comes along to this document would have no idea that is there. At least there are breadcrumbs to find the macros from my sheet buttons and they can be followed to see what is happening.

If you can give me an example of how to use subprocess from within a VB macro I would love to try that.

1 Like

Yes, if you need the macros into document, you need attach into it, but, this can automate too.

With Python you can call script python too and get the result. I’m sorry only I know this with Python, not with Basic.

So after much messing around, looks like to execute a python script from the shell using bash you have to preface the script with “python”.

This doesn’t work:
ExeLinuxCommandSync(“echo_test.py hello > echopy.txt”)

This works:
ExeLinuxCommandSync(“python echo_test.py hello > echopy.txt”)

(see my original post for the ExeLinuxCommandSync function code)

There is still something in the real script that isn’t letting it return a value, but this at least gets the simple script working as expected.

No, with Shell never get an answer like you need, look documentation:

https://help.libreoffice.org/Basic/Shell_Function_Runtime