python 文本文件中按每秒记录数_限制Python上每秒的HTTP请求数

您可以使用标准Python库中的信号量对象:

python doc

或者,如果您想直接处理线程,可以使用wait([timeout])。在

没有与Python捆绑的库可以在以太网或其他网络接口上工作。你能用的最低的是插座。在

根据你的答复,我有个建议。请注意活动的\u计数。仅用于测试脚本是否只运行两个线程。在这个例子中,它们是三个,因为第一个是你的脚本,然后你有两个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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值