I am looking for a way to run a file through the Terminal, but instead of typing it in, I want to run a python script that runs the file through the Terminal for me.
This code should run through the terminal:
cd LCD-show
sudo ./LCD35-show
I already tried this and run it in Python:
import os
os.system("./LCD35-show")
But that does not work. How can I solve this problem?
Try this on for size:
import subprocess
p1 = subprocess.run("cd LCD-show ; sudo ./LCD35-show", shell=True, text=True, capture_output=True)
print(p1.returncode)
print(p1.stdout)
print(p1.stderr)
The shell=True
option runs the whole arg thru the shell so multiple commands separated by semicolon work. text=True
means treat stdout
and stderr
as strings, not bytes. Lastly, capture_output=True
means actually capture stdout
and stderr
as properties.
If you have a whole file of commands in myFile.sh
, it's basically the same thing. Just be aware of exec permissions on myFile.sh
and any PATH
considerations; you might have to do ./myFile.sh
:
p1 = subprocess.run("myFile.sh", shell=True, text=True, capture_output=True)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.