2015-07-21 86 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