如何从 shell 中脱离出来,同时从 python 子进程循环



我用shell脚本多次启动python脚本。在运行一些 python 脚本后,我想从 while-loop 中挣脱出来。在我当前的解决方案中,我从 python 发送了一个 shell 脚本 PID 的终止信号。但我想防止父进程在子进程完成之前死亡。

我当前的 shell 脚本:

#!/bin/sh
while true
do
  python3 my_py_script.py $$
done

我的python脚本的相关部分:

import signal
import sys
...
shell_script_pid = int(sys.argv[1])
...
if ..something..:
   os.kill(shell_script_pid, signal.SIGTERM)
   sys.exit('python script end')

我会建议一个解决方案,您不会杀死父进程,而是使用退出代码。

外壳脚本:

#!/bin/sh
while python3 my_py_script.py; do :; done

蟒蛇脚本:

if ..something..:
   sys.exit('python script ends with errorcode 1')

python 脚本的默认退出代码为 0。因此,当它在最后退出时,shell 循环将再次运行。当它以sys.exit('python script ends with errorcode 1')退出时,壳环将停止。

https://docs.python.org/3/library/sys.html#sys.exit:

[...]如果传递了其他类型的对象,则 None 等效于传递零,并且任何其他对象将打印到 stderr,并导致退出代码 1。特别是,sys.exit("某些错误消息"(是在发生错误时退出程序的快速方法。

如果存在其他错误,这不应该导致 shell 脚本退出循环,则可以将精确的错误代码与 sys.exit(123)python3 my_py_script.py; lastexitcode=$? 一起使用。

最新更新