我编写了一个脚本,用于从文件中获取 URL 并同时向所有 URL 发送 HTTP 请求。我现在想限制每秒 HTTP 请求数和每个接口的带宽(eth0
, eth1
等)在会话中。有什么办法可以在Python上实现这一点吗?
您可以使用 Semaphore 对象,它是标准 Python 库的一部分:蟒蛇文档 https://docs.python.org/2/library/threading.html#semaphore-objects
或者,如果您想直接使用线程,可以使用 wait([timeout])。
没有与 Python 捆绑在一起的可以在以太网或其他网络接口上工作的库。最低的可以是套接字。
根据您的回复,这是我的建议。注意 active_count。仅使用它来测试您的脚本是否只运行两个线程。在这种情况下,它们将是三个,因为第一个是您的脚本,然后您有两个 URL 请求。
import time
import requests
import threading
# Limit the number of threads.
pool = threading.BoundedSemaphore(2)
def worker(u):
# Request passed URL.
r = requests.get(u)
print r.status_code
# Release lock for other threads.
pool.release()
# Show the number of active threads.
print threading.active_count()
def req():
# Get URLs from a text file, remove white space.
urls = [url.strip() for url in open('urllist.txt')]
for u in urls:
# Thread pool.
# Blocks other threads (more than the set limit).
pool.acquire(blocking=True)
# Create a new thread.
# Pass each URL (i.e. u parameter) to the worker function.
t = threading.Thread(target=worker, args=(u, ))
# Start the newly create thread.
t.start()
req()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)