想象一下我的功能如下:
def func1():
return int(requests.get('https://www.random.org/integers/?num=1&min=0&max=10&col=1&base=10&format=plain&rnd=new').text)
我希望将此函数调用三次,对响应求和,然后返回平方或简单的值。我怎么能这样做,所以三个函数调用是异步的,但它等待它们全部返回,在Javascript中的一个Promise.all?
我正在使用Python 2.
答案 0 :(得分:2)
你需要使用线程,最简单的方法是通过multiprocessing.pool.ThreadPool
包(不要让它欺骗你,尽管在包中,它不是多处理的):
import requests
from multiprocessing.pool import ThreadPool
# let's make it a bit more flexible
RANDOM_URL = 'https://www.random.org/integers/'
RANDOM_PARAMS = {"num": 1, "min": 0, "max": 10, "col": 1, "base": 10,
"format": "plain", "rnd": "new"}
def func1(*args): # args added to account for the dummy payload from pool.map
return int(requests.get(RANDOM_URL, params=RANDOM_PARAMS).text)
pool = ThreadPool(processes=3)
response_sum = sum(pool.map(func1, range(3)))
print("Squared response: {}".format(response_sum**2))
答案 1 :(得分:1)
出于您的目的,我正在修改功能:
def func1():
page = requests.get('https://www.random.org/integers/?num=1&min=0&max=10&col=1&base=10&format=plain&rnd=new').text
num = extract_num(page) # Any parsing function that extracts the number and converts it to an integer type.
cumulative += num # Sums up
然后,使用线程:
import threading
cumulative = 0
for i in range(3): # Gets random numbers asynchronously.
threading.Thread(target=func1).start()
print cumulative
答案 2 :(得分:0)
根据您的喜好,如果您对安装第三方后端模块https://pypi.python.org/pypi/futures没有问题,您还可以使用concurrent.futures
作为更高级别的界面,以避免处理线程和拥有API更类似于您在问题中提到的承诺/期货:
from concurrent.futures import ThreadPoolExecutor
import requests
def func1():
return int(requests.get('https://www.random.org/integers/?num=1&min=0&max=10&col=1&base=10&format=plain&rnd=new').text)
ex = ThreadPoolExecutor()
f1 = ex.submit(func1)
f2 = ex.submit(func1)
f3 = ex.submit(func1)
print(f1.result(), f2.result(), f3.result())