简体   繁体   English

python runpy.run_module 退出代码

[英]python runpy.run_module exit code

Is it possible to get the exit code from a module called through runpy.run_module()?是否可以从通过 runpy.run_module() 调用的模块中获取退出代码?

I wish to replace my exit_code = subprocess.call('py -m mymodule') with runpy.run_module('mymodule') and still get the exit_code value.我希望用runpy.run_module('mymodule')替换我的exit_code = subprocess.call('py -m mymodule') runpy.run_module('mymodule') exit_code = subprocess.call('py -m mymodule') runpy.run_module('mymodule')并仍然获得exit_code值。

Where mymodule is a directory containing a python script __main__.py which just does sys.exit(1)其中mymodule是一个包含 python 脚本__main__.py的目录, sys.exit(1)执行sys.exit(1)

Testing runpy.run_module('mymodule') in an interactive shell closes that shell.在交互式 shell 中测试runpy.run_module('mymodule')关闭该 shell。 I could not find any documentation on that behavior.我找不到有关该行为的任何文档。 To me it looks like that the difference between using subprocess.call and runpy.run_module is running it as a program or function.对我来说,这看起来两者的区别subprocess.callrunpy.run_module运行它作为一个程序或功能。 If that is the case then the behavior is explained and it is unlikely that I can use runpy.run_module if I need the exit code.如果是这种情况,则会解释该行为,如果需要退出代码,则不太可能使用runpy.run_module Can anyone confirm this, possibly with a link to some documentation where I could have found it.任何人都可以确认这一点,可能带有指向我可以找到它的某些文档的链接。

This morning it hit me, so I tested a solution and it worked:今天早上它击中了我,所以我测试了一个解决方案并且它起作用了:

import runpy

try:
    runpy.run_module('mymodule')
except SystemExit as exeption:
    exitcode = exeption.code
else:
    exitcode = 0

The catch is that you have to handle every exception thrown in the module.问题是您必须处理模块中抛出的每个异常。 I am only handling the SystemExit exception in my example, as it is the only exception that I am interested in.在我的示例中,我只处理SystemExit异常,因为它是我唯一感兴趣的异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM