Python 在后台运行函数并继续执行程序
我试图在后台运行一个函数,同时继续用python编写上述代码 我想在后台运行的函数来自Python 在后台运行函数并继续执行程序,python,multithreading,Python,Multithreading,我试图在后台运行一个函数,同时继续用python编写上述代码 我想在后台运行的函数来自socket。正在查找特定数据以切断程序 以下是函数: def receive(): host = "" port = 13000 buf = 1024 addr = (host,port) Sock = socket(AF_INET, SOCK_DGRAM) Sock.bind(addr) (data, addr) = Sock.recvfrom(buf
socket
。正在查找特定数据以切断程序
以下是函数:
def receive():
host = ""
port = 13000
buf = 1024
addr = (host,port)
Sock = socket(AF_INET, SOCK_DGRAM)
Sock.bind(addr)
(data, addr) = Sock.recvfrom(buf)
return data
以下是我要运行的代码:
while True:
r = receive()
if r == "stop":
break
#Cannot get past here, because of the function running.
#Should loop over and over, until stop data is received
print "Running program"
我已经尝试过线程化,使用
r=threading.Thread(target=receive())
,但毫无乐趣。您无法从被调用线程的目标函数返回调用线程。相反,您需要一些线程间通信系统。下面是一个使用Python的队列
在两个线程之间传递接收到的数据报的示例。我使用了threading.Event
来通知接收器线程何时应该停止
#!/usr/bin/env python
import socket
import threading
from queue import Empty, Queue
class DatagramReceiver(threading.Thread):
def __init__(self, stop, queue):
super().__init__()
self._stop = stop
self._queue = queue
def run(self):
with socket.socket(AF_INET, SOCK_DGRAM) as sock:
sock.bind(('', 13000))
while not self._stop.is_set():
data = sock.recvfrom(1024)[0]
if data == 'stop':
self._stop.set()
break
self._queue.put(data)
def main():
stop = threading.Event()
queue = Queue()
reader = DatagramReceiver(stop, queue)
reader.deamon = True
reader.start()
while not stop.is_set():
user_input = input('Press RETURN to print datagrams, or q quit')
if user_input == 'q':
break
while True:
try:
datagram = queue.get_nowait()
except Empty:
break
print(datagram)
stop.set()
reader.join()
新手错误:
r = threading.Thread(target=receive())
我没有从receive()
上取下括号:
target=receive()
应该是target=receive
@PeterWood,谢谢!现在我遇到了Python[Errno 98]地址已经在使用的问题。同一主机+端口组合上只能同时打开一个套接字。在启动线程之前打开套接字一次,并将其传递给后台线程。停止消息的可能副本应该来自另一个python脚本。考虑到这一点,我不确定如何实现您的脚本@PeterSuttonI已经编辑了代码,这样一条“stop”消息将导致工作线程停止(进而停止主线程)。主线程能够干净地停止工作线程仍然是一个好主意(因此我仍然使用stop事件)。
r = threading.Thread(target=receive)