'NameError: name 'buf' is not defined
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import socket
import time
import multiprocessing
import threading
b=1
global buf
def data_accept():
global buf
# IPV4,TCP协议
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定ip和端口,bind接受的是一个元组
sock.bind(('127.0.0.1', 6010))
# 设置监听,其值阻塞队列长度,一共可以有5+1个客户端和服务器连接
sock.listen(5)
# 等待客户段请求
connection, address = sock.accept()
a = [1, 2, 3, 4]
while True:
buf = connection.recv(40960)
def main():
global buf
thread_data = threading.Thread(target=data_accept)
thread_data.start()
while True:
print(":", float(buf.decode('utf-8')))
if __name__ == '__main__':
main()
Solution 1:[1]
No need to use the global keyword when initializing the variable. Just use buf, for example, buf = None
import socket
import time
import multiprocessing
import threading
b=1
buf = None
def data_accept():
global buf
# IPV4,TCP??
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# ??ip????bind????????
sock.bind(('127.0.0.1', 6010))
# ???????????????????5+1??????????
sock.listen(5)
# ???????
connection, address = sock.accept()
a = [1, 2, 3, 4]
while True:
buf = connection.recv(40960)
print('asdf')
def main():
global buf
thread_data = threading.Thread(target=data_accept)
thread_data.start()
while True:
if buf is not None:
print(":", float(buf.decode('utf-8')))
if __name__ == '__main__':
main()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bryan Woo |
