【发布时间】:2018-01-30 03:38:04
【问题描述】:
我正在尝试:
- 启动后台进程(python 脚本)
- 运行一些 bash 命令
- 然后在前台任务完成后发送 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