簡體   English   中英

Ctrl-C 從 python 到 bash

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM