python - 如何从 python 子进程中退出 shell while 循环?

标签 python python-3.x shell

我使用 shell 脚本多次启动 python 脚本。运行一些 python 脚本后,我想跳出 while 循环。在我当前的解决方案中,我从 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')

最佳答案

我建议您不要终止父进程,而是使用退出代码。

shell 脚本:

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

Python 脚本:

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

Python脚本的默认退出代码是0。所以当它最后退出时,shell循环将再次运行。当它以 sys.exit('python scriptends with errorcode 1') 退出时,shell 循环将停止。

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

[...] If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.

如果出现其他错误,但不会导致 shell 脚本退出循环,可以使用 sys.exit(123)python3 my_py_script 使用精确的错误代码.py; Lastexitcode=$?.

关于python - 如何从 python 子进程中退出 shell while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48462927/

相关文章:

java - 利用现有数据库的应用程序的 Web 框架?

python - 在 python 中处理长整数除法

python - 使用 PIL 显示 RGB 图像的问题

python - 从一个容器到另一个容器运行命令

python - 奇怪的编码错误,作为可执行文件与 shell 脚本调用时的行为不同

linux - 使用 Expect 的 SFTP

python - 如何使用 python opencv 测量同一图像中两条线之间的角度?

python - 无法使用 AWS Lambda 构建 Scikit 学习包

用于重定向流的 Linux 脚本

Javascript 相当于 Python 的 urlparse.parse_qs()?