<分区>
我正在尝试:
- 启动后台进程(python 脚本)
- 运行一些 bash 命令
- 然后在前台任务完成后发送 control-C 关闭后台进程
我尝试过的最小示例 - Python test.py
:
import sys
try:
print("Running")
while True:
pass
except KeyboardInterrupt:
print("Escape!")
Bash 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)