Python returning values from infinite loop thread

风格不统一 提交于 2019-12-11 06:00:23

问题


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


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.


回答1:


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)

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.

See: https://docs.python.org/3/library/queue.html



来源:https://stackoverflow.com/questions/48429653/python-returning-values-from-infinite-loop-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!