[英]Ctrl-C from python to bash
我有一個 bash shell 腳本,它在無限循環中調用 Python 腳本:
while true; do python testomat.py ; done
Python 腳本testomat.py
:
try:
do_something()
except KeyboardInterrupt:
print 'exit'
finally:
raise SystemExit
我遇到的問題是我無法通過Ctrl-C
來阻止它。 我唯一的機會: Ctrl-z
然后kill -TERM %1
假設我沒有其他作業正在運行。 Python 是否必須以某種方式將Ctrl-C
傳播給父級,或者我該如何阻止它?
I know I could run the endless loop inside Python, but I actually do more in both the bash shell script and the Python script which both must continue to exist.
在 Python 腳本中設置退出狀態,並在 Bash 腳本中捕獲它。 我會使用 130,因為這就是像grep
這樣的 coreutils 並find
用處。
except KeyboardInterrupt:
sys.exit(130)
while true; do
python testomat.py
case $? in
130) break ;;
esac
done
您會注意到您通常可以中斷 shell 循環。 例如,當您按下 Ctrl-C 時,此循環將正常退出:
while true; do sleep 10; done
一個父進程——這里是 shell——可以判斷一個子進程是否正常退出,或者它是否被信號殺死。 如果它被信號殺死,shell 將認為信號未處理並停止循環和/或腳本。 如果孩子收到信號但正常退出,shell 會認為它已處理並繼續。
當一個進程想要進行一些清理時,它必然會處理信號,因此不會被殺死。 因此,規范的 Unix 行為是,在清理完成后,卸載信號處理程序並重新殺死自己:
import time
import os
import signal
try:
time.sleep(10);
except KeyboardInterrupt:
print('exit')
signal.signal(signal.SIGINT, signal.SIG_DFL)
os.kill(os.getpid(), signal.SIGINT)
由於死因已正確傳遞回 shell,因此您現在可以按 Ctrl-C 退出while true; do python yourfile.py; done
while true; do python yourfile.py; done
while true; do python yourfile.py; done
循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.