嵌入在bash Python脚本,不退出 [英] Python script embedded in bash, does not exit

查看:131
本文介绍了嵌入在bash Python脚本,不退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题。我有一个在调用它python脚本bash脚本。 Python脚本执行成功,但从来没有完全终止

I'm having a curious problem. I have a bash script that is calling a python script within it. The python script executes successfully, but never fully terminates

Bash脚本内容:

#! /usr/bin/env bash
python python_script.py
echo "bar"

Python脚本内容:

content of Python script:

#Much stuff
sys.exit("The python script just ended")

我希望看到的终端为:

What I expect to see on termination would be:

>The python script just ended
>bar

我反而得到的是:

What I instead get is:

>The python script just ended

如果我的键盘中断,在bash继续为:

If I keyboard interrupt, the bash continues as:

^C>bar

怎么办?显然,出口是否正确地调用,并且存在,并在bash脚本调用Python脚本的输出语句之间没有任何东西。

What gives? Clearly the exit is calling properly, and there is nothing between that and the output statement in the bash script that called the python script.

(我不一定能上的很多东西的运作细节在python脚本,因为我修改现有code,我不完全理解。我大部分时间留在运作仅在脚本,修改的输出比什么格式化,但我很乐意尝试并为您提供所需)

(I can't necessarily give specifics on the workings of the "Much stuff" in the python script, as I'm modifying existing code that I don't fully understand. I've mostly left the workings of the script alone, and modified output more than anything for formatting, but I'm happy to try and provide you with any additional information requested)

推荐答案

什么 sys.exit()确实是抛出类型的 SystemExit 。如果你的脚本是赶上这个例外,它会继续执行过去 sys.exit()

What sys.exit() does is throw an exception of type SystemExit. If your script were to catch this exception, it would continue executing past sys.exit().

此外,如果您有非守护线程,这可能是$ P $从终止pventing的过程。

Also, if you have non-daemon threads, these could be preventing the process from terminating.

如果是这样的话,您可以把它们变成守护线程,或以某种方式信号向他们表示要退出脚本,并让他们自行关闭。

If that's the case, you can either turn them into daemon threads, or somehow signal to them that you wish to exit the script, and let them shut themselves down.

最后,还有 os._exit() ,但你不应该诉诸这一点。

Finally, there's os._exit(), but you should not have to resort to that.

这篇关于嵌入在bash Python脚本,不退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆