Python 在后台获取数据-可能使用线程
我想使用Python3定期从网站获取一些数据。同时,我想处理来自上一个请求的数据 当没有响应或发生错误时,我希望使用前面的有效值 以下是一个例子:Python 在后台获取数据-可能使用线程,python,multithreading,python-3.x,urllib,Python,Multithreading,Python 3.x,Urllib,我想使用Python3定期从网站获取一些数据。同时,我想处理来自上一个请求的数据 当没有响应或发生错误时,我希望使用前面的有效值 以下是一个例子: import threading import urllib.request import urllib.error import time start_time = time.time() req = urllib.request.Request("http://fake-response.appspot.com/") text = "Be
import threading
import urllib.request
import urllib.error
import time
start_time = time.time()
req = urllib.request.Request("http://fake-response.appspot.com/")
text = "Before response"
def fetch():
try:
response = urllib.request.urlopen(req)
return response.read().decode('latin1')
except (urllib.error.HTTPError, urllib.error.URLError) as e:
print(e)
print("Initial text is \"%s\"" % text)
text = threading.Thread(target=fetch)
while time.time() - start_time < 15:
print("%s - text: \"%s\"" % (time.strftime("%H:%M:%S"), text))
# This should print '<TIME> - text: "Before response" for ten seconds
# After that, '<TIME> - text: {"response":"This request has finished sleeping for 10 seconds"}' should be displayed
time.sleep(0.5)
我发现了,但我不知道这是否适用
我更喜欢一个简单但不涉及额外库的解决方案。我试图保持较低的内存占用,因为这只是我项目的一个副业。不知道这是否是一个好的做法,但我找到了一个更精细的基于类的设计的解决方案:
import threading
import urllib.request
import urllib.error
import time
start_time = time.time()
req = urllib.request.Request("http://fake-response.appspot.com/")
class Fetcher(threading.Thread):
def __init__(self):
self.text = "No response yet!"
super().__init__()
def run(self):
try:
response = urllib.request.urlopen(req)
self.text = response.read().decode('latin1')
except (urllib.error.HTTPError, urllib.error.URLError) as e:
print(e)
fetcher = Fetcher()
print("Initial text is \"%s\"" % fetcher.text)
fetcher.start()
text = fetcher.text
while time.time() - start_time < 15:
print("%s - text: \"%s\"" % (time.strftime("%H:%M:%S"), fetcher.text))
# This should print '<TIME> - text: "No response yet!"' for ten seconds
# After that, '<TIME> - text: {"response":"This request has finished sleeping for 10 seconds"}' should be displayed
time.sleep(0.5)
对于3.4+,我将尝试使用新的asyncio模块定期获取新数据。不过,我必须重新阅读文档,以建议代码。@TerryJanReedy观点很好,但我使用3.2,使用另一个模块时有点保守。。。