[英]Using Python to run a file with the terminal
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.我正在寻找一种通过终端运行文件的方法,但我不想输入它,而是想运行一个 python 脚本,该脚本为我通过终端运行文件。
This code should run through the terminal:此代码应通过终端运行:
cd LCD-show
sudo ./LCD35-show
I already tried this and run it in Python:我已经尝试过这个并在 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. shell=True
选项通过 shell 运行整个 arg,因此用分号分隔的多个命令起作用。 text=True
means treat stdout
and stderr
as strings, not bytes. text=True
意味着将stdout
和stderr
视为字符串,而不是字节。 Lastly, capture_output=True
means actually capture stdout
and stderr
as properties.最后, capture_output=True
意味着实际捕获stdout
和stderr
作为属性。
If you have a whole file of commands in myFile.sh
, it's basically the same thing.如果你在myFile.sh
中有一个完整的命令文件,那基本上是一样的。 Just be aware of exec permissions on myFile.sh
and any PATH
considerations;请注意myFile.sh
的 exec 权限和任何PATH
考虑事项; you might have to do ./myFile.sh
:你可能需要做./myFile.sh
:
p1 = subprocess.run("myFile.sh", shell=True, text=True, capture_output=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.