我有一个主python脚本,它使用subprocess.check_call
运行另外几个较小的脚本。
我不想看到这些较小脚本的输出,所以我使用stdout=DEVNULL
我可以通过捕捉returncode
得到CalledProcessError
,但我想抓住传递的消息,如果脚本以sys.exit('my exit message')
结尾
我似乎无法抓住那条消息 - 这在Python中是否可能?我不想写一个文件来读取退出消息。
这就是我在master.py
中尝试过的:
import subprocess
try:
subprocess.check_call('python scripttoberun.py', shell=True, stdout=subprocess.DEVNULL)
except subprocess.CalledProcessError as e:
print(e.args)
print(e.output)
print(e.stderr)
print(e.returncode)
print(e.cmd)
在我的scripttoberun.py
:
import sys
print('starting... ')
sys.exit('im quitting')
但我似乎无法抓住'im quitting
消息?
我只能看到这个输出:
(1, 'python scripttoberun.py')
None
None
1
python scripttoberun.py
这可能吗?
非常感谢!
我设法让这个工作,我不得不将stderr=PIPE
参数传递给check_output
函数。然后通过在.decode()
异常上使用stderr
我可以得到消息。 PERFECTO
这是我在master.py
的代码:
from subprocess import check_output, CalledProcessError, PIPE
try:
check_output('python scripttoberun.py', stderr=PIPE)
print('Program ran successfully')
except CalledProcessError as e:
print('Program did not run successfully: ', e.stderr.decode())