Python 从无限循环线程返回值

Python returning values from infinite loop thread

所以对于我的程序,我需要检查本地网络上的客户端,它有一个 Flask 服务器 运行。此 Flask 服务器正在 returning 一个可以更改的数字。

现在要检索该值,我使用请求库和 BeautifulSoup.
我想在脚本的另一部分使用检索到的值(同时不断检查其他客户端)。为此,我想我可以使用线程模块。
然而,问题是,线程只有 returns 它是完成循环时的值,但循环需要是无限的。

这是我目前得到的:

import threading
import requests
from bs4 import BeautifulSoup

def checkClient():
    while True:
        page = requests.get('http://192.168.1.25/8080')
        soup = BeautifulSoup(page.text, 'html.parser')
        value = soup.find('div', class_='valueDecibel')
        print(value)

t1 = threading.Thread(target=checkClient, name=checkClient)
t1.start()


有谁知道如何 return 打印的值到另一个函数吗?当然,您可以将 requests.get url 替换为某种值变化很大的 API。

你需要一个 Queue 和一些监听队列的东西

import queue
import threading
import requests
from bs4 import BeautifulSoup

def checkClient(q):
    while True:
        page = requests.get('http://192.168.1.25/8080')
        soup = BeautifulSoup(page.text, 'html.parser')
        value = soup.find('div', class_='valueDecibel')
        q.put(value)

q = queue.Queue()
t1 = threading.Thread(target=checkClient, name=checkClient, args=(q,))
t1.start()

while True:
    value = q.get()
    print(value)

Queue 是线程安全的,允许来回传递值。在您的情况下,它们仅从线程发送到接收器。

参见:https://docs.python.org/3/library/queue.html