使用子进程运行bash命令时,我可能会遇到命令无效的情况.在这种情况下,bash将返回错误消息.我们怎样才能抓住这条消息?我想将此消息保存到日志文件中.以下是一个示例,我尝试在不存在的目录中列出文件.try:subprocess....

使用子进程运行bash命令时,我可能会遇到命令无效的情况.在这种情况下,bash将返回错误消息.我们怎样才能抓住这条消息?我想将此消息保存到日志文件中.
以下是一个示例,我尝试在不存在的目录中列出文件.
try:
subprocess.check_call(["ls", "/home/non"])
df = subprocess.Popen(["ls", "/home/non"], stdout=subprocess.PIPE)
output, err = df.communicate()
# process outputs
except Exception as error:
print error
sys.exit(1)
Bash会打印“ls:无法访问/ home / non:没有这样的文件或目录”.我怎样才能收到此错误消息? except行捕获的错误明显不同,它说“Command'[‘ls’,’/ home / non’]’返回非零退出状态2”.
解决方法:
您可以将stderr重定向到文件对象:
from subprocess import PIPE, CalledProcessError, check_call, Popen
with open("log.txt", "w") as f:
try:
check_call(["ls", "/home/non"], stderr=f)
df = Popen(["ls", "/home/non"], stdout=PIPE)
output, err = df.communicate()
except CalledProcessError as e:
print(e)
exit(1)
输出到log.txt:
ls: cannot access /home/non: No such file or directory
如果你想要的信息除外:
try:
check_call(["ls", "/home/non"])
df = Popen(["ls", "/home/non"], stdout=PIPE)
output, err = df.communicate()
except CalledProcessError as e:
print(e.message)
对于python 2.6,e.message将不起作用.您可以使用类似版本的python 2.7的check_output,它将与python 2.6一起使用:
from subprocess import PIPE, CalledProcessError, Popen
def check_output(*args, **kwargs):
process = Popen(stdout=PIPE, *args, **kwargs)
out, err = process.communicate()
ret = process.poll()
if ret:
cmd = kwargs.get("args")
if cmd is None:
cmd = args[0]
error = CalledProcessError(ret, cmd)
error.out = out
error.message = err
raise error
return out
try:
out = check_output(["ls", "/home"], stderr=PIPE)
df = Popen(["ls", "/home/non"], stdout=PIPE)
output, err = df.communicate()
except CalledProcessError as e:
print(e.message)
else:
print(out)
沃梦达教程
本文标题为:python – 保存子进程命令的错误消息


基础教程推荐
猜你喜欢
- 如果没有管理员权限,如何在Windows中安装Python(任何版本)? 2023-11-15
- linux的shell后门尝试以及python快速转C 2023-09-03
- Python和Shell交互工具 ShellPy 2023-11-11
- 如何利用python写GUI及生成.exe可执行文件 2023-08-05
- Python教程之基本运算符的使用(上) 2022-10-20
- tkFileDialog无法在Windows上将结果转换为Python列表 2023-11-14
- 进程与子进程(python3入门) 2023-09-04
- python-此代码效率太低,如何增加内存和执行效率? 2023-11-13
- 使Cython在Anacondas,Windows 7 64位上与Python 3.4一起使用 2023-11-11
- python可视化大屏库big_screen示例详解 2023-08-11