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

Kou*_*aki 2 python subprocess

我正在尝试使用 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'))
Run Code Online (Sandbox Code Playgroud)

大致是这样的。

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

如果正常执行,我能收到输出吗?如果出现错误,我能收到子进程的错误消息吗?

wp-*_*com 5

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

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
Run Code Online (Sandbox Code Playgroud)

设置check=True为在返回码非零时抛出错误(这表明发生了某些错误)。

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