【问题标题】:Bash: Waiting on a background python process [duplicate]Bash:等待后台python进程[重复]
【发布时间】:2018-01-30 03:38:04
【问题描述】:

我正在尝试:

  1. 启动后台进程(python 脚本)
  2. 运行一些 bash 命令
  3. 然后在前台任务完成后发送 control-C 以关闭后台进程

我尝试过的最小示例 - Python test.py:

import sys

try:
    print("Running")
    while True:
        pass
except KeyboardInterrupt:
    print("Escape!")

重击test.sh:

#!/bin/bash

python3 ./test.py &
pid=$!

# ... do something here ...
sleep 2

# Send an interrupt to the background process
# and wait for it to finish cleanly
echo "Shutdown"
kill -SIGINT $pid
wait

result=$?
echo $result
exit $result

但是 bash 脚本似乎一直处于等待状态,并且 SIGINT 信号没有被发送到 python 进程。

我正在使用 Mac OS X,并且正在寻找适用于 linux + mac 上的 bash 的解决方案。

编辑: Bash 正在发送中断,但 Python 在作为后台作业运行时没有捕获它们。通过在 Python 脚本中添加以下内容来修复:

import signal
signal.signal(signal.SIGINT, signal.default_int_handler)

【问题讨论】:

  • 感谢@Ruslan - 我能够通过在 python 中重新添加信号处理程序来解决我的问题。

标签: python linux bash macos shell


【解决方案1】:

重点是SIGINT是用来终止前台进程的。您应该直接使用kill $pid 来终止后台进程。

顺便说一句,kill $pid 等于 kill -15 $pid 或 kill -SIGTERM $pid。

更新

你可以使用signal模块来处理这种情况。

import signal
import sys
def handle(signum, frame):
    sys.exit(0)
signal.signal(signal.SIGINT, handle)
print("Running")
while True:
    pass

【讨论】:

  • 我想发送一个中断(相当于按下 control-C),我可以在 python 中捕获它以干净地关闭。 SIGTERM 只是终止后台进程。
  • 好的,我明白你的意思了,我会更新我的答案。
猜你喜欢
  • 1970-01-01
  • 2015-06-22
  • 2014-11-08
  • 1970-01-01
  • 2011-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-12
相关资源
最近更新 更多