从另一个主脚本调用时从一个python脚本获取退出消息

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

我有一个主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

这可能吗?

非常感谢!

python subprocess exit sys
1个回答
0
投票

我设法让这个工作,我不得不将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())

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