在Python中,你可以使用subprocess
模塊來執行外部命令并處理命令執行中的信號
import subprocess
import signal
def handle_signal(signum, frame):
print(f"Signal {signum} received, terminating the subprocess...")
# 在這里你可以執行其他操作,例如清理資源等
raise SystemExit(signum)
# 注冊信號處理函數
signal.signal(signal.SIGTERM, handle_signal)
signal.signal(signal.SIGINT, handle_signal)
# 使用subprocess執行外部命令
cmd = "sleep 10" # 這里可以替換為你想要執行的外部命令
process = subprocess.Popen(cmd, shell=True)
try:
process.wait()
except SystemExit as e:
print(f"Subprocess terminated with code {e}")
在這個示例中,我們首先導入了subprocess
和signal
模塊。然后,我們定義了一個名為handle_signal
的信號處理函數,該函數將在接收到指定的信號時被調用。在這個函數中,我們可以執行任何需要的操作,例如清理資源等。
接下來,我們使用signal.signal()
函數注冊了handle_signal
函數作為SIGTERM
和SIGINT
信號的處理函數。這意味著當這些信號被發送給Python進程時,它們將被handle_signal
函數處理。
最后,我們使用subprocess.Popen()
函數執行了一個外部命令(在這個示例中是sleep 10
),并使用process.wait()
等待命令執行完成。如果命令被信號終止,process.wait()
將引發一個SystemExit
異常,我們可以在except
塊中捕獲并處理它。