2015-07-21 87 views
2

我在信號處理程序中更改全局變量並在主程序中輪詢它。但是這個值在主線程中並沒有改變。Python - 輪詢變量

是否有一個限定符,我需要使用它來使其變成一個易變(如Java)變量?

這裏的程序:

test.py每當我按

import time 
import signal 

def debug(): 
    closeSession = False 

    def sigint_handler(signal, frame): 
     global closeSession 

     print('Breaking the poll...') 
     closeSession=True 

    signal.signal(signal.SIGINT, sigint_handler) 

    # Start a program... 

    while not closeSession: 
     time.sleep(1) 
     print('Polling... closeSession = %r' % closeSession) 

    print('Exiting! Bye.') 
    # Sent 'quit' to stdin of the program 

if __name__ == "__main__": 
    debug() 

sigint_handler()被稱爲按Ctrl +çcloseSession新的值不會在主線程中使用。

我得到以下輸出:

$蟒蛇test.py
投票... closeSession =假
投票... closeSession =假

我按下Ctrl鍵 + C

^CBreaking投票...
投票... closeSession =假

按下Ctrl鍵+Ç,再次

^CBreaking投票..
Polling ... closeSession = False

按下Ctrl鍵+Ç,再次

^CBreaking投票...
投票... closeSession =假
投票... closeSession =假

+0

非常好的格式**第一個問題**。 –

+0

@MohitJain感謝:) –

回答

1

的問題是範圍。

debug()函數內部,您沒有聲明closeSession作爲全局函數,這意味着您有兩個變量,分別稱爲closeSession。在debug()函數中一個全局和一個作用域。在sigint_handler()函數中,您已明確指示使用全局函數,該函數由外部函數中的作用域所映射。

您可以通過在debug()宣佈轉讓前的全球解決這個問題:

def debug(): 
    global closeSession 
    closeSession = False 
    ... 

順便說一句,您的代碼不工作在Windows上,它拋出一個IO錯誤,因爲睡眠功能被中斷。解決方法,我的工作是:

... 
while not closeSession: 
    try: 
     time.sleep(1) 
    except IOError: 
     pass 
    print('Polling... closeSession = %r' % closeSession) 
... 

這不是很漂亮,但它的工作原理。

+0

Thant工程。感謝您的澄清。 –

1

在訪問變量之前,您必須先設置global closeSession,否則您將創建一個具有相同名稱的局部變量,並且循環將永不結束。

試試這個:

import time 
import signal 

def debug(): 
    global closeSession # <-- this was missing 
    closeSession = False 

    def sigint_handler(signal, frame): 
     global closeSession 
     print('Breaking the poll...') 
     closeSession=True 

    signal.signal(signal.SIGINT, sigint_handler) 

    # Start a program... 

    while not closeSession: 
     time.sleep(1) 
     print('Polling... closeSession = %r' % closeSession) 

    print('Exiting! Bye.') 
    # Sent 'quit' to stdin of the program 

if __name__ == "__main__": 
    debug() 
+0

該功能被按下Ctrl + C, 被稱爲「打破民意調查...」正在打印。 –

+0

您的代碼有效,謝謝。 –

+0

Aah :-)對不起沒有。在debug()中的賦值之前,你是否嘗試設置'global closeSession'? – adrianus