我正在尝试:
- 启动后台进程(Python 脚本(
- 运行一些 bash 命令
- 然后在前台任务完成后发送 control-C 关闭后台进程
我尝试过的最小示例 - Pythontest.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)
重点是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