Calling python script from macro in StarBasic

Creating a macro - Writing a Script - Using the API (OpenOffice Basic, Python, BeanShell, JavaScript)
Locked
zwora
Posts: 35
Joined: Sun Oct 07, 2018 8:21 am

Calling python script from macro in StarBasic

Post by zwora »

Hi.

I would like to run a python script (that is in the same directory as my .ods file) from macro in oo basic. I was tyrying to use shell() function, but it does not work as I wish to.

i.e.:

Code: Select all

shell("cd C:/Users/myusr/temp & python test.py")
gives a prompt: Error: File not found

however when I open cmd window and type:

Code: Select all

cd C:\Users\myusr\temp & python test.py
it works fine.

Even:

Code: Select all

path = ThisComponent.getURL()
arr=Split(path, "myfile.ods")
path=arr(0)
path = path + "test.py"
url = ConvertToURL(path)
shell(url)
Gives the same error (however I need to run it like: "python test.py" as my python script has some libraries imported).

And I wouldn't like to use a python macro instead of oo basic as I definately need to use external python file and other macros in this .ods document are oo basic.

Any help appreciated.
Last edited by MrProgrammer on Mon Mar 21, 2022 10:08 pm, edited 2 times in total.
Reason: Moved topic from Calc forum to Macros and UNO API
Windows 7/Windows 10, Open Office 4.1.2
zwora
Posts: 35
Joined: Sun Oct 07, 2018 8:21 am

Re: Calling python script from macro in basic

Post by zwora »

I partially resolved the problem:

Code: Select all

Dim obj As Object
obj = createUnoService("com.sun.star.system.SystemShellExecute")
obj.execute(python_path,path,0)
It works unless I don't use imports from external libraries. But unfortunately I do, so I need to run python from my project directory.

My path cannot be like:

Code: Select all

path = " C:\Users\myusr\temp\test.py"
I need to go to project directory first (like "cd C:\Users\myusr\temp\") and then run "python test.py". But how to do that using obj.execute()?
Windows 7/Windows 10, Open Office 4.1.2
User avatar
RoryOF
Moderator
Posts: 35089
Joined: Sat Jan 31, 2009 9:30 pm
Location: Ireland

Re: Calling python script from macro in basic

Post by RoryOF »

A guess: Perhaps your problem may be the space character between " and C?
Apache OpenOffice 4.1.15 on Xubuntu 22.04.5 LTS
User avatar
robleyd
Moderator
Posts: 5415
Joined: Mon Aug 19, 2013 3:47 am
Location: Murbko, Australia

Re: Calling python script from macro in basic

Post by robleyd »

Or does myuser have a space or special character in it?
Slackware 15 64 bit
Apache OpenOffice 4.1.15
LibreOffice 25.2.5.2; SlackBuild for 25.2.5 by Eric Hameleers
---------------------
Roses are Red, Violets are Blue]
Unexpected '{' on line 32
.
zwora
Posts: 35
Joined: Sun Oct 07, 2018 8:21 am

Re: Calling python script from macro in basic

Post by zwora »

No it doesn't. It is not an issue with syntax.

If I type in cmd:

Code: Select all

python C:\Users\myusr\temp\test.py
it prompts that libraries are missing.

However typing in cmd:

Code: Select all

cd C:/Users/myusr/temp & python test.py
runs perfectly.

So the challenge is to run the file from inside C:/Users/myusr/tem directory.

It has to be something like:

Code: Select all

shell("cd C:/Users/myusr/temp/ & python_path/python.exe test.py")
(the above does not work - file not found is prompted).


But anyway thanks for your answer.
Windows 7/Windows 10, Open Office 4.1.2
zwora
Posts: 35
Joined: Sun Oct 07, 2018 8:21 am

Re: Calling python script from macro in basic

Post by zwora »

RoryOF wrote:A guess: Perhaps your problem may be the space character between " and C?
It is the typo just here in the post. In my code there is no space. But thank you.
Windows 7/Windows 10, Open Office 4.1.2
User avatar
MrProgrammer
Moderator
Posts: 5313
Joined: Fri Jun 04, 2010 7:57 pm
Location: Wisconsin, USA

Re: Calling python script from macro in basic

Post by MrProgrammer »

zwora wrote:I was tyrying to use shell() function, but it does not work as I wish to.
Functions work as they are documented, not how you wish them to work.
If wishes were horses, beggars would ride
zwora wrote:shell("cd C:/Users/myusr/temp & python test.py")
gives … File not found
The documentation for the Shell function says:
   Syntax: Shell (Pathname As String[, Windowstyle As Integer][, Param As String][, bSync])
   Pathname: Complete path and program name of the program that you want to start

You did not provide the name of a program file. You provided a statement for cmd.exe. Of course the system cannot find the file named "cd C:/Users/myusr/temp & python test.py".

If you need to change the directory before calling Python, the simple solution is to create, say with Notepad, a file which contains two lines, one to issue the cd command and one to call your Python program. Then point the Shell function at the file you created.
 Edit: 2022-03-21: Specifically, create Foo.cmd then use Basic statement: SHELL("C:\«YourPath»\Foo.cmd") 
As I recall, when the file extension is .cmd, Windows knows that it's a cmd.exe batch file. 
Or, if you know where cmd.exe is located you might be able to pass a parameter to it with something like Shell("C:\Windows\System32\cmd.exe",6,"/c ""cd C:\Users\myusr\temp & python test.py""",TRUE). I may not have that syntax quite right since I haven't used damned Windows for over a decade. And C:\Windows\System32 might be the wrong path for your system.
zwora wrote:obj = createUnoService("com.sun.star.system.SystemShellExecute")
obj.execute(python_path,path,0)

works unless I don't use imports from external libraries. But unfortunately I do, so I need to run python from my project directory.
I do not use Python, but surely the language provides a way for programs to control what libraries are available for imports. Learning how to do that would be a Python question, so if you want assistance with it I recommend that you consult a Python forum. This one supports OpenOffice and derivatives. I have no recommendations to you for a Python forum, but a web search will find one.

If this solved your problem please go to your first post use the Edit button and add [Solved] to the start of the subject field. Select the green checkmark icon at the same time.
Mr. Programmer
AOO 4.1.7 Build 9800, MacOS 13.7.6, iMac Intel.   The locale for any menus or Calc formulas in my posts is English (USA).
Mountaineer
Posts: 335
Joined: Sun Sep 06, 2020 8:27 am

Re: Calling python script from macro in basic

Post by Mountaineer »

MrProgrammer wrote: surely the language provides a way for programs to control what libraries are available for imports. Learning how to do that would be a Python question,
As zwora already has an installed python he can use his own libraries or install third-party libs with the usual command-line tool pip. Same is true for most AOO/LO installs on Linux, as they can use the python installed in the OS.

But he could also use libraries with the internal bundled python of Aoo/LO. But there is no pip available, so you have to install the lib yourself in the pythonpath wich your Office sees (not in the Python of an external installation).

J.

PS My experience is with LibreOffice only, when it comes to python. I switched before I started with Macros.
LibreOffice 7.6 on Windows 10pro and other Versions parallel
zwora
Posts: 35
Joined: Sun Oct 07, 2018 8:21 am

Re: Calling python script from macro in StarBasic

Post by zwora »

The simple solution is to create, say with Notepad, a file which contains two lines, one to issue the cd command and one to call your Python program. Then point the Shell function at the file you created.
This solution does not run commands from inside the file. But maybe I've got wrong code:

Code: Select all

p = ThisComponent.getURL()
arr = Split(p,"temp.ods")
arr1 = arr(0)
arr2 = Split(arr1,"///")
path = arr2(1) + "commands.txt"
 shell("C:\Windows\system32\cmd.exe" & " " & path)
The path to file is ok (I printed it and checked). In my commands.txt I've got:

Code: Select all

cd C:\Users\jarek\OneDrive\trading\dziecioltemp\temp\
nul > filename.txt
python test.py
The second command is just for making sure, that commands are executed. But they don't as the filename.txt is not created.

The second solution also does not work for me. The error is: "fatal python error init_fs_encoding failed to get the python codec of the filesystem encoding" And further invstigation leads to conclusion that OO uses python2 (C:\Program Files (x86)\OpenOffice 4\program\python-core-2.7.18) and my script uses python 3.
I do not use Python, but surely the language provides a way for programs to control what libraries are available for imports.
And it does. But I need to run script from inside the directory where my python script is.
Windows 7/Windows 10, Open Office 4.1.2
User avatar
Villeroy
Volunteer
Posts: 31346
Joined: Mon Oct 08, 2007 1:35 am
Location: Germany

Re: Calling python script from macro in StarBasic

Post by Villeroy »

Please, edit this topic's initial post and add "[Solved]" to the subject line if your problem has been solved.
Ubuntu 18.04 with LibreOffice 6.0, latest OpenOffice and LibreOffice
zwora
Posts: 35
Joined: Sun Oct 07, 2018 8:21 am

Re: Calling python script from macro in StarBasic

Post by zwora »

That would be a good solution if I could just call functions from my python script one by one. But I can't. My script draws svg images using pycairo library based on some data provided. So I need to do some calulations first (quite a lot of them) to get coordinates of the drawn objects and then create cairo object and use some methods on that to draw all the elements. So the script needs to be run as whole code.

The script anyway is complete, so I can put data (dimensions and some control variables) inside and just run it. The OO spreadsheet is just for easier UI. Instead of putting data to py script I would like to put them into OO calc document then send it to csv file and run the python script to collect data from csv and make to rest of the job. I can of course make a web app for that, but I would like to have many instances for this app made by just copying it to a new directory and working separately.
Windows 7/Windows 10, Open Office 4.1.2
Mountaineer
Posts: 335
Joined: Sun Sep 06, 2020 8:27 am

Re: Calling python script from macro in StarBasic

Post by Mountaineer »

zwora wrote: ...
This solution does not run commands from inside the file. But maybe I've got wrong code:

Code: Select all

p = ThisComponent.getURL()
arr = Split(p,"temp.ods")
arr1 = arr(0)
arr2 = Split(arr1,"///")
path = arr2(1) + "commands.txt"
 shell("C:\Windows\system32\cmd.exe" & " " & path)
I didn't test yours, but it may be as simple as renaming commands.txt to .BAT as this is the expected
extension for DOS-style scripting. The following works for me on Win7 and Win10 as part of a sequence to
save reports, do some XML-mmagic by script and sending results by mail.

Code: Select all

	stFeld=  convertToUrl("C:\Users\myhome\localpath\XML\"+"_exp2XML.bat")
REM	MsgBox(stFeld)
	IF stFeld <> "" THEN
		oShell = createUnoService("com.sun.star.system.SystemShellExecute")
		oShell.execute(stFeld,,0)
		END IF

J.

PS: For your first syntax I found "<command1>&&<command2>&&<command3>" so perhaps try with && instead of &
(similiar to the usage of %% in BATCH instead of single % )
PPS: Have you tried to call the batch directly shell("command.bat") instead of
shell -> cmd.exe -> bat
LibreOffice 7.6 on Windows 10pro and other Versions parallel
zwora
Posts: 35
Joined: Sun Oct 07, 2018 8:21 am

Re: Calling python script from macro in StarBasic

Post by zwora »

zwora wrote:PPS: Have you tried to call the batch directly shell("command.bat") instead of shell -> cmd.exe -> bat
I've done as you proposed and commands are now run one by one. Thank you.

But there is still a problem with trying to use python 2 (which is stored in oo directory (C:\Program Files (x86)\OpenOffice 4\program\python-core-2.7.18\) instead of python3 installed im my system. Is there any way to enforce the use of python3?
Windows 7/Windows 10, Open Office 4.1.2
User avatar
Zizi64
Volunteer
Posts: 11490
Joined: Wed May 26, 2010 7:55 am
Location: Budapest, Hungary

Re: Calling python script from macro in StarBasic

Post by Zizi64 »

Is there any way to enforce the use of python3
If I know it exactly, the LibreOffice installs and uses a Python 3.x version package.
Tibor Kovacs, Hungary; LO7.5.8 /Win7-10 x64Prof.
PortableApps/winPenPack: LO3.3.0-7.6.2;AOO4.1.14
Please, edit the initial post in the topic: add the word [Solved] at the beginning of the subject line - if your problem has been solved.
musikai
Volunteer
Posts: 294
Joined: Wed Nov 11, 2015 12:19 am

Re: Calling python script from macro in StarBasic

Post by musikai »

I can run any file with its associated program with:

Code: Select all

oSyShell = CreateUnoService("com.sun.star.system.SystemShellExecute")
oSyShell.execute(converttourl(path & file), "", 0)
Don't know if that means in your example that the .py file will be executed "locally".
Win7 Pro, Lubuntu 15.10, LO 4.4.7, OO 4.1.3
Free Project: LibreOffice Songbook Architect (LOSA)
http://struckkai.blogspot.de/2015/04/li ... itect.html
zwora
Posts: 35
Joined: Sun Oct 07, 2018 8:21 am

Re: Calling python script from macro in StarBasic

Post by zwora »

Zizi64 wrote:If I know it exactly, the LibreOffice installs and uses a Python 3.x version package.
I've installed LO and now it uses python3. Thank you. But I've got same problem as before - the library is missing. It goes to a dicrctory with python file (using cd) and runs python command. But then there is an error "ModuleNot Found". But fi I do the same from command line (I mean typing the same commands as in the .bat file) everything works. I tested also using command (pip install pycairo) for installing this library (not effective, but did it just to check) in a .bat file. And it doesn't see the package installation program pip (as Mountaineer mentioned earlier). It means that if I try to run commands this way (by macro and .bat file) the PATH environment variable is not seen. So I need to force LO to use python I've installed, or letit use python within LO but make the libraries visible to it.
For that second solution I reinstalled pycairo within nLO lib dir by pip install --target=... But some files have names with some additions based on my python version (python not witin LO), so running causes errors. After changing the names there are another errors.
Windows 7/Windows 10, Open Office 4.1.2
User avatar
Villeroy
Volunteer
Posts: 31346
Joined: Mon Oct 08, 2007 1:35 am
Location: Germany

Re: Calling python script from macro in StarBasic

Post by Villeroy »

Either you find some way to add libraries to LibreOffice's Python runtime or you switch the office suite to your system's Python runtime. https://www.openoffice.org/udk/python/p ... #replacing describes how to do the latter with OpenOffice.org 2. May be it still works with LibreOffice.
Please, edit this topic's initial post and add "[Solved]" to the subject line if your problem has been solved.
Ubuntu 18.04 with LibreOffice 6.0, latest OpenOffice and LibreOffice
zwora
Posts: 35
Joined: Sun Oct 07, 2018 8:21 am

Re: Calling python script from macro in StarBasic

Post by zwora »

Villeroy wrote:Either you find some way to add libraries to LibreOffice's Python runtime or you switch the office suite to your system's Python runtime. https://www.openoffice.org/udk/python/p ... #replacing describes how to do the latter with OpenOffice.org 2. May be it still works with LibreOffice.
I've done all the steps described in the lin and for both OO and LO and in both cases program starts as usual, but if I try to add macro to element like button it shuts down immediately with no warning. Macro editor works fine, I can add subroutines there, but any attempt of binding the macro to control element finishes with that sudden closing. And if I open document that already has working macros in it, it opens, warns about macros usage (immediate level of macros security) and shuts down the same way as described above.

My pythonloader.uno.ini file looks as follows (C:/Users/myusr/AppData/Local/Programs/Python/Python38-32 is the directory where my python is placed:

Code: Select all

PYUNO_LOADER_PYTHONHOME=file:///C:/Users/myusr/AppData/Local/Programs/Python/Python38-32
PYUNO_LOADER_PYTHONPATH=file:///C:/Users/myusr/AppData/Local/Programs/Python/Python38-32/Lib $ORIGIN
The above address together with: C:\Program Files\LibreOffice\program are added to PATH variable and new variable is created for C:\Program Files\LibreOffice\program (tried both names for it: PYUNO_LOADER_PYTHONPATH and just PYTHONPATH).
Windows 7/Windows 10, Open Office 4.1.2
Locked