[英]How to know and prevent an error with terminal commands from python?
Making a program which can open apps upon listening to commands.制作一个可以在听命令时打开应用程序的程序。 The app name is stored in variable 'a'.
应用程序名称存储在变量“a”中。 And then opened with the following line:
然后使用以下行打开:
os.system("open /Applications/" + a + ".app")
But sometimes it is possible that 'a' does not exist on the system, say 'music' for which the console prints:但有时系统上可能不存在“a”,例如控制台打印的“音乐”:
The file /Applications/music.app does not exist.
And the python code stops entirely. python 代码完全停止。
How can I know that the console gave this error and prevent the program from stopping?我怎么知道控制台给出了这个错误并阻止程序停止?
subprocess is more powerful than os.system
, the stdout and stderr of subprocess can be ignored with subprocess subprocess比 os.system 更强大,
os.system
的 stdout 和 stderr 可以用 subprocess 忽略
import subprocess
res=subprocess.run(["open", "/Applications/" + a + ".app"])
print(res.returncode)
use res.returncode
to get the execute result(none zero value shows that the sub process has encountered errors).使用
res.returncode
获取执行结果(无零值表示子进程遇到错误)。
Maybe you could try to use the try
/ except
commands to handle errors in python: https://docs.python.org/3/tutorial/errors.html . Maybe you could try to use the
try
/ except
commands to handle errors in python: https://docs.python.org/3/tutorial/errors.html .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.