Python从无限循环线程返回值 [英] Python returning values from infinite loop thread

查看:198
本文介绍了Python从无限循环线程返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,对于我的程序,我需要检查本地网络上运行的Flask服务器的客户端.该Flask服务器返回的数字可以更改.

现在要检索该值,我使用了请求库和BeautifulSoup.
我想在脚本的另一部分中使用检索到的值(同时不断检查其他客户端).为此,我认为我可以使用线程模块.
问题是,线程仅在完成循环后才返回其值,但是循环必须是无限的.

这是我到目前为止所得到的:

So for my program I need to check a client on my local network, which has a Flask server running. This Flask server is returning a number that is able to change.

Now to retrieve that value, I use the requests library and BeautifulSoup.
I want to use the retrieved value in another part of my script (while continuously checking the other client). For this I thought I could use the threading module.
The problem is, however, that the thread only returns it's values when it's done with the loop, but the loop needs to be infinite.

This is what I got so far:

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()


有谁知道如何在这里将打印的值返回到另一个函数?当然,您可以使用某些值会发生很大变化的API来替换request.get网址.


Does anyone know how to return the printed values to another function here? Of course you can replace the requests.get url with some kind of API where the values change a lot.

推荐答案

您需要Queue和正在队列中监听的内容

You need a Queue and something listening on the 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是线程安全的,并允许来回传递值.就您而言,它们只是从线程发送到接收者.

The Queue is thread safe and allows to pass values back and forth. In your case they are only being sent from the thread to a receiver.

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

这篇关于Python从无限循环线程返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆