2014-09-26 90 views
0

在Windows中,我試圖創建一個等待SIGINT信號的python進程。當它接收到SIGINT時,我希望它只是打印一條消息並等待SIGINT的另一個出現。所以我使用了信號處理程序。Windows中的信號處理

這是我的signal_receiver.py代碼。

import signal, os, time 

def handler(signum, frame): 
    print 'Yes , Received', signum 

signal.signal(signal.SIGINT, handler) 
print 'My process Id' , os.getpid() 

while True: 
    print 'Waiting for signal' 
    time.sleep(10) 

當這個進程在運行,我剛剛從其他Python過程中使用發送SIGINT這個procees,

os.kill(pid,SIGINT)

但是,當signal_receiver.py收到SIGINT時,它只是退出執行。但預期的行爲是在處理函數內部打印消息並繼續執行。

有人可以幫我解決這個問題。它在windows中是一個限制,因爲在linux中同樣工作正常。

在此先感謝。

+0

Windows沒有信號。 Python正在模擬它們,但可能不支持跨進程。考慮使用其中一種本地IPC方法。 – 2014-09-28 00:37:11

+0

[根據此答案](http://stackoverflow.com/a/26053962/886887)Python不支持跨進程信號。 – 2014-09-28 00:44:27

回答

1

當您按下CTRL + C時,進程收到一個SIGINT,並且您正確捕獲它,否則它會拋出一個KeyboardInterrupt錯誤。

在Windows上,當time.sleep(10)中斷時,儘管您捕獲了SIGINT,但它仍會拋出InterruptedError。只需添加一個try /除了內部time.sleep語句來捕獲這個異常,例如:

import signal 
import os 
import time 

def handler(signum, frame): 
    if signum == signal.SIGINT: 
     print('Signal received') 

if __name__ == '__main__': 
    print('My PID: ', os.getpid()) 
    signal.signal(signal.SIGINT, handler) 

    while True: 
     print('Waiting for signal') 
     try: 
      time.sleep(5) 
     except InterruptedError: 
      pass 

注意:上Python3.x測試,它也應該在2.x協同工作。

+0

它不適用於Windows 7,Python 2.7 – wap26 2016-07-18 13:28:33