有什么方法可以像 node.js 那样制作异步 python3 吗?
我想要一个最小的例子,我已经尝试了下面的方法,但仍然可以使用同步模式。
import urllib.request
class MyHandler(urllib.request.HTTPHandler):
@staticmethod
def http_response(request, response):
print(response.code)
return response
opener = urllib.request.build_opener(MyHandler())
try:
opener.open('http://www.google.com/')
print('exit')
except Exception as e:
print(e)
如果异步模式有效,print('exit')
应该首先显示。
有人能帮忙吗?
最佳答案
使用线程(基于你自己的代码):
import urllib.request
import threading
class MyHandler(urllib.request.HTTPHandler):
@staticmethod
def http_response(request, response):
print(response.code)
return response
opener = urllib.request.build_opener(MyHandler())
try:
thread = threading.Thread(target=opener.open, args=('http://www.google.com',))
thread.start() #begin thread execution
print('exit')
# other program actions
thread.join() #ensure thread in finished before program terminates
except Exception as e:
print(e)
关于python - 使用 python3 的异步 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25197108/