Reputation: 27
I would like to launch a process from a Python script on a raspberry pi 3 raspbian.
On Windows, the following code would work:
import os
def openFile():
try:
os.startfile("/home/pi/Desktop")
except:
print("invalid path")
But here I get back invalid path.
Can you tell me how to fix this and also how to open applications?
I remember that in windows:
There's Notepad.exe
in a path and I can open it but what should I say for Linux? I mean what is the .exe
in Linux and can I open it?
Upvotes: 1
Views: 682
Reputation: 1398
As far as I understand, what you're trying to do is called not open
but execute
. So you could find more info about that by searching for "python execute file on Linux". Despite this, you are trying to execute a directory, not a file. So, here is an example of what I'd do:
import subprocess
subprocess.call(['/bin/ls', '-l'])
This will call the executable file ls
located at the /bin
folder and provide it with one argument: -l
. It will list files in your current directory (however, remember that you shouldn't use ls
for that purpose, this is just an example. If you want to list files in a directory, there are special functions for that in Python).
Speaking about file extensions, the executable file on Linux (similar to Windows' .exe file) is called an ELF file, which does not have a canonical extension. In fact, Linux in general cares about extensions much less, than Windows. If you want to know more about which else files can be executed on Linux, execute permissions etc, please, search for info on the internet and/or ask a question at https://superuser.com)
Upvotes: 2
Reputation: 347
os.startfile
is only available for Windows. You should use instead the subprocess
library. Try this platform-independant solution from @user4815162342 which I adapted
import os, sys, subprocess
def open_file(filename):
if sys.platform == "win32":
os.startfile(filename)
else:
opener = "open" if sys.platform == "darwin" else "xdg-open"
subprocess.run([opener, filename])
If your file is just a bash script, you can replace the subprocess.run
line by
subprocess.run(["bash", filename])
Upvotes: 2