【问题标题】:How to break out from a shell while loop from a python child process?如何从 python 子进程的 shell while 循环中跳出?
【发布时间】:2018-01-26 14:06:44
【问题描述】:

我用一个 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')

【问题讨论】:

  • 您不能将 Python 代码包装在一个 while 循环中并管理您的 Python 代码中的迭代吗?
  • 为什么需要在您的子进程之一完成之前阻止父进程退出?
  • @Evan 防止僵尸进程。
  • @franciscosollima 这也是一个解决方案。但我更喜欢每次运行都使用新的流程。

标签: python python-3.x shell


【解决方案1】:

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

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-loop 将再次运行。当它以sys.exit('python script ends with errorcode 1') 退出时,shell 循环将停止。

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

[...] 如果传递了另一种类型的对象,None 相当于传递零,并且任何其他对象都打印到 stderr 并导致退出代码为 1。特别是 sys.exit("some error message") 是发生错误时退出程序的快速方法。

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

【讨论】:

  • 我不懂你的shell脚本。您使用空循环体设置为条件“运行 python 脚本”?
  • 没错,在shell脚本中,条件只是一个命令,当命令的退出码为0时条件为真,当退出码不是0时条件为假跨度>
  • 那么python脚本运行一次?
  • 在 while 循环中,每个循环都会运行条件。 shell 脚本意味着: 1. 运行 python3 my_py_script.py, 2. 检查退出代码是否不为零 3. 当退出代码不为零时退出循环 4. 在循环内不执行任何操作; 5. 从第 1 步重新开始
  • python脚本的默认退出代码是0。所以当它在最后退出时循环将再次运行,当它以sys.exit('python script ends with errorcode 1')退出时,shell循环将停止
猜你喜欢
  • 2013-01-13
  • 2021-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多