我希望有一个线程在后台等待UDP数据包,而在没有收到数据包时我希望脚本能够做另外的事情。但是当我启动线程时,脚本会等待UDP数据包并停止。
import threading
import socket
def rec_UDP():
while True:
# UDP commands for listening
UDP_PORT = 5005
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('10.0.0.15', UDP_PORT))
data, addr = sock.recvfrom(1024)
print "received message:", data
return data
# The thread that ables the listen for UDP packets is loaded
listen_UDP = threading.Thread(target=rec_UDP())
listen_UDP.start()
data = 'Nothing received'
while True:
print 'The packet received is: ' + data
答案 0 :(得分:2)
通过在函数之后附加()
,代码调用直接阻塞主线程的函数,而不是在分离的线程中运行函数。
删除函数名后的()
。
listen_UDP = threading.Thread(target=rec_UDP)
答案 1 :(得分:0)
这不适用于 Python 3,但它让我走上了正确的道路。这是我的 Python 3 版本。
#!/usr/bin/python3
import _thread, time, socket
data = '' # Declare an empty variable
# UDP setup for listening
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('', 12345)) # I'm using port 12345 to bind to
# Define a function for the thread
def listening_thread():
global data # data needs to be defined as global inside the thread
while True:
data_raw, addr = sock.recvfrom(1024)
data = data_raw.decode() # My test message is encoded
print ("Received message inside thread:", data)
try:
_thread.start_new_thread(listening_thread, ())
except:
print ("Error: unable to start thread")
quit()
while 1:
print ('Now I can do something useful while waiting in the main body.')
if data:
print ('THE PACKET RECEIVED BY THE MAIN BODY IS: ' + data)
data = '' # Empty the variable ready for the next one
time.sleep(2)