我想检查Python的子进程是否成功或是否发生错误

问题描述 投票:1回答:2

我正在尝试使用python子进程创建代码生成代码。

#code = 'print("hey")' #OK
code = 'print"hey")'   #SyntaxError
with open(filename, 'w') as f:
    f.write(code)

proc = s.Popen(['python',filename], stdout=s.PIPE, stderr=s.STDOUT)
stdout_v, stderr_v = proc.communicate('')
print(stdout_v.decode('utf8'))

它大致是这样的。

目前,即使子进程正常运行或发生语法错误,子进程的返回值也包含在stdout_v中,并且它不能区分它们。

如果输出正常,是否可以接收输出,如果发生错误,可以从子进程接收错误消息?

python subprocess
2个回答
4
投票

在Python 3.5+中使用子进程的推荐方法是使用run function

proc = s.run(['python',filename], stdout=s.PIPE, stderr=s.PIPE, check=False)
stdout_v, stderr_v, = proc.stdout, proc.stderr
return_code = proc.return_code

如果返回码非零,则设置check=True以抛出错误(这表示发生了一些错误)。

在旧版本的Python中,我通常更喜欢使用check_outputcall函数。如果检测到非零退出代码,Check_output将抛出错误,而调用函数将正常继续。


0
投票

从文件

https://docs.python.org/2/library/subprocess.html

您可以通过检查命令的有效性

subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

使用参数运行命令。等待命令完成。如果返回码为零则返回,否则引发CalledProcessError。 CalledProcessError对象将在returncode属性中包含返回代码。

Return code 0= Sucess

如果你想看到命令的输出

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)

使用参数运行命令并将其输出作为字节字符串返回。

© www.soinside.com 2019 - 2024. All rights reserved.