[英]Run function in background and continue with program
I am trying to run a function in the background, whilst continuing with said code in python. 我试图在后台运行一个函数,同时继续使用python中的上述代码。
The function I want to run in the background is from socket
. 我想在后台运行的功能是来自socket
。 Looking for specific data to cut the program off. 寻找特定数据以切断程序。
Here is the function: 这是函数:
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
Here is the code I want to run: 这是我要运行的代码:
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"
I have tried threading, with r = threading.Thread(target=receive())
with no joy. 我试过线程,没有喜悦r = threading.Thread(target=receive())
。
You can't return to the invoking thread from an invoked thread's target function. 您不能从被调用线程的目标函数返回到调用线程。 Instead, you need some inter-thread communication system. 相反,您需要一些线程间通信系统。 Below, is an example using Python's Queue
to pass received datagrams between the two threads. 下面是使用Python的Queue
在两个线程之间传递接收到的数据报的示例。 I've used a threading.Event
to signal when the receiver thread should stop. 我使用了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()
Rookie error: 新秀错误:
r = threading.Thread(target=receive())
I did not take the brackets off the receive()
: 我没有把括号从receive()
移开:
r = threading.Thread(target=receive)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.