您应该为此查看subprocess
模块。有一种check_call
方法可以查看退出代码(这是一种方法,还有其他方法)。正如手册中提到的:
运行带参数的命令。等待命令完成。如果返回码为零,则返回,否则引发 CalledProcessError。CalledProcessError 对象将在 returncode 属性中具有返回码
这方面的一个例子是:
import subprocess
command=["ls", "-l"]
try:
exit_code=subprocess.check_call(command)
# Do something for successful execution here
print("Program run")
except subprocess.CalledProcessError as e:
print "Program exited with exit code", e.returncode
# Do something for error here
这还将包括输出,您可以将其重定向到文件或像这样抑制:
import subprocess
import os
command=["ls", "-l"]
try:
exit_code=subprocess.check_call(command, stdout=open(os.devnull, "w"))
# Do something for successful execution here
print("Program run")
except subprocess.CalledProcessError as e:
print "Program exited with exit code", e.returncode
# Do something for error here
下面是一个带有非零退出代码的调用示例:
import subprocess
import os
command=["grep", "mystring", "/home/cwgem/testdir/test.txt"]
try:
exit_code=subprocess.check_call(command, stdout=open(os.devnull, "w"))
# Do something for successful execution here
print("Program run")
except subprocess.CalledProcessError as e:
print "Program exited with exit code", e.returncode
# Do something for error here
输出:
$ python process_exitcode_test.py
Program exited with exit code 1
这被捕获为您可以如上所述处理的异常。请注意,这不会处理访问被拒绝或找不到文件等异常。您需要自己处理它们。