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

时间:2019-04-30 07:35:34

标签: python subprocess exit sys

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

这可能吗?

非常感谢!

1 个答案:

答案 0 :(得分:0)

我设法使它起作用,我不得不将stderr=PIPE参数传递给check_output函数。然后,通过对.decode()异常使用stderr可以得到消息。完美

这是我在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())