[英]How to exit from nested python scripts?
I have two python scripts call a.py
and b.py
. 我有两个名为
a.py
和b.py
python脚本。
From inside a.py
, I am giving command 从
a.py
内部,我正在发出命令
os.system('python b.py')
If some exception is found in b.py
, I want the complete execution of both a.py
and b.py
to be halted. 如果在
b.py
发现了一些异常,我希望停止a.py
和b.py
的完整执行。 Is there a way to do that? 有没有办法做到这一点?
I am not importing b.py
in a.py
. 我没有在
a.py
导入b.py
I am simply calling it using os.system()
. 我只是使用
os.system()
调用它。
How can the same be achieved even if I import the other script? 即使导入其他脚本,如何也可以实现相同目的?
os.system() returns the (encoded) process exit value. os.system()返回(编码的)进程退出值。 0 means success.
0表示成功。
I would rather reccomend the subprocess Module since it is more powerful. 我宁愿推荐子流程模块,因为它更强大。 Take a look at
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
. 看一下
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
。
Good luck. 祝好运。
If you import a module b
that might raise an exception which you won't handle, either let the exception halt the execution by not handling it, or, handle it and exit
yourself. 如果导入的模块
b
可能引发您将无法处理的异常,请通过不对其进行处理来使该异常停止执行,或者处理该异常并exit
自己。
If you opt for calling os.system
check the error code returned; 如果您选择调用
os.system
请检查返回的错误代码。 if Python doesn't exit gracefully (ie an exception was raised) it is going to be a non 0
value. 如果Python无法正常退出(即引发了异常),则它将为非
0
值。 You can test on and act accordingly: 您可以进行测试并采取相应措施:
if os.system('python b.py'):
# exit from script a.by
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.