I'm new with Python and I've encountered this error this afternoon. I tried to fix this by adding global
before the previous
variable but I continue to get this error:
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:
A sample of the code I did:
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:])
You have nested scopes here:
def main(argv):
...
global previous
...
def send():
...
if data != previous:
Declaring global in main
function does not apply to the local in send
function.
You could move the global declaration for the previous
into the start of the send
method. You can remove the global declaration for bridge
completely.
Better yet, refactor your code not to use nested scopes and global variables!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.