有没有办法像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')
应首先显示。
有人可以帮忙吗?
答案 0 :(得分:3)
使用线程(基于您自己的代码):
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)