本地变量' ...'在分配之前引用

时间:2017-01-18 22:08:45

标签: python python-2.7

我是Python的新手,今天下午我遇到了这个错误。我尝试通过在global变量之前添加previous来解决此问题,但我仍然遇到此错误:

Traceback (most recent call last):
  File "send.py", line 76, in <module>
main(sys.argv[1:])
  File "send.py", line 34, in main
send()
  File "send.py", line 29, in send
    if data != previous:

我所做的代码示例:

import socket
import sys
import getopt
import time
import threading

sys.path.insert(0, '/usr/lib/python2.7/bridge/') 

from bridgeclient import BridgeClient as bridgeclient

def main(argv):
    global bridge
    global previous

    try:                    
        # Create a UDP socket.
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        server_address = ('192.168.1.100', 9050)

        bridge = bridgeclient()
        previous = ""

        # Send data  
        def send():         
            data = bridge.get("data")   

            if data != previous:                    
                sent = sock.sendto(data, server_address)                                
                previous = data
                threading.Timer(0.2, send).start()

        send()

    finally:
        sock.close()

if __name__ == "__main__":
    main(sys.argv[1:])

1 个答案:

答案 0 :(得分:2)

您在此处嵌套了范围:

def main(argv):
    ...
    global previous
    ...
    def send():
        ...
        if data != previous:

main函数中声明全局不适用于send函数中的本地。

您可以将previous的全局声明移动到send方法的开头。您可以完全删除bridge的全局声明。

更好的是,重构代码不要使用嵌套作用域和全局变量!