Python - 轮询一个变量

Python - Polling a variable

我更改了信号处理程序中的全局变量并在主程序中轮询它。但是在主线程中这个值并没有改变。

是否需要使用限定符来使其成为易变的(如 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 + C 时都会被调用,但 closeSession 的新值不是在主线程中使用。

我得到以下输出:

$ python test.py
Polling... closeSession = False
Polling... closeSession = False

我按Ctrl + C

^CBreaking the poll...
Polling... closeSession = False

Ctrl + C,再次

^CBreaking the poll...
Polling... closeSession = False

Ctrl + C,再次

^CBreaking the poll...
Polling... closeSession = False
Polling... closeSession = False

您必须在访问变量之前设置 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()

范围问题

debug() 函数中,您没有将 closeSession 声明为全局变量,这意味着您有两个名为 closeSession 的变量。一个全局的,一个在 debug() 函数内。在 sigint_handler() 函数内部,您已明确指示使用全局函数,它被外部函数中的作用域函数所遮蔽。

您可以通过在 debug() 中赋值之前声明全局来解决此问题:

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

顺便说一下,您的代码在 windows 上不起作用,它会抛出 IOError,因为睡眠函数被中断。对我有用的解决方法是:

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

虽然不漂亮,但很管用。