Python请求:不要等待请求完成

在Bash中,可以通过追加在后台执行命令&。如何在Python中完成?

while True:

data = raw_input('Enter something: ')

requests.post(url, data=data) # Don't wait for it to finish.

print('Sending POST request...') # This should appear immediately.

回答:

我用multiprocessing.dummy.Pool。我在模块级别创建一个单例线程池,然后用于pool.apply_async(requests.get,

[params])启动任务。

该命令给了我一个未来,我可以将它无限期地与其他未来添加到列表中,直到我想收集全部或部分结果为止。

multiprocessing.dummy.Pool 出于所有逻辑和理由,是一个THREAD池而不是一个进程池。

示例(只要安装了请求,就可以在Python 2和3中使用):

from multiprocessing.dummy import Pool

import requests

pool = Pool(10) # Creates a pool with ten threads; more threads = more concurrency.

# "pool" is a module attribute; you can be sure there will only

# be one of them in your application

# as modules are cached after initialization.

if __name__ == '__main__':

futures = []

for x in range(10):

futures.append(pool.apply_async(requests.get, ['http://example.com/']))

# futures is now a list of 10 futures.

for future in futures:

print(future.get()) # For each future, wait until the request is

# finished and then print the response object.

这些请求将同时执行,因此运行所有十个请求所花的时间不应超过最长的一个。该策略将仅使用一个CPU内核,但这不会成为问题,因为几乎所有时间都将花费在等待I /

O上。

以上是 Python请求:不要等待请求完成 的全部内容, 来源链接: utcz.com/qa/407132.html

回到顶部