我正在打开一个有100,000个URL的文件.我需要向每个URL发送HTTP请求并打印状态代码.我正在使用Python 2.6,到目前为止,我看到了Python实现线程/并发的许多令人困惑的方式.我甚至看过python concurrence库,但无法弄清楚如何正确编写这个程序.有没有人遇到过类似的问题?我想通常我需要知道如何尽快在Python中执行数千个任务 - 我想这意味着'同时'.
我正在编程服务器,似乎我的连接数量有限,因为我的带宽没有饱和,即使我已经将连接数设置为"无限制".
如何增加或消除我的Ubuntu Linux盒一次可以打开的最大连接数?操作系统是否限制了这个,还是路由器或ISP?或者是别的什么?
我想非常快地连接到很多不同网站的列表.我使用asyncio以异步方式执行此操作,现在想要添加超时,以便在需要花费太长时间来响应时忽略连接.
我该如何实现?
import ssl
import asyncio
from contextlib import suppress
from concurrent.futures import ThreadPoolExecutor
import time
@asyncio.coroutine
def run():
while True:
host = yield from q.get()
if not host:
break
with suppress(ssl.CertificateError):
reader, writer = yield from asyncio.open_connection(host[1], 443, ssl=True) #timout option?
reader.close()
writer.close()
@asyncio.coroutine
def load_q():
# only 3 entries for debugging reasons
for host in [[1, 'python.org'], [2, 'qq.com'], [3, 'google.com']]:
yield from q.put(host)
for _ in range(NUM):
q.put(None)
if __name__ == "__main__":
NUM = 1000
q = …Run Code Online (Sandbox Code Playgroud) 如下所示,我想与特定IP范围内的许多PC进行通信.
My PC ---+------> Client A PC
+------> Client B PC
+------> Client C PC
.................
+------> Client Z PC
Run Code Online (Sandbox Code Playgroud)
因为有太多客户端要沟通,所以我尝试了多线程.socket.connect()不断产生超时错误.如果我在单线程中尝试它,那就没问题了.
我用Google搜索并找到了以下内容:
说在某些平台上,套接字模块可能是线程不安全的.
所以我将代码更改为多处理.但是它仍然会产生相同的错误.
在以下代码示例中,test_single()完成正常.test_mp()和test_mt()都会导致超时错误.
你有没有经历过这种异常行为?测试环境是Windows XP SP3,python 2.5.4.还尝试了python 2.6.6和2.7.0,同样的错误.
import multiprocessing
import Queue
import socket
import threading
PROCESS_NUM = 5
PORT = 8888
def search_proc(ip):
try:
csock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
csock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
csock.settimeout(5.0)
csock.connect((ip, PORT))
csock.shutdown(socket.SHUT_RDWR)
csock.close()
return ip, "ok"
except socket.error, msg:
return ip, "fail", msg
def mp_connect(ip_range):
pool = multiprocessing.Pool( PROCESS_NUM )
for output in …Run Code Online (Sandbox Code Playgroud) 我写了大约50个类,用于连接和使用机械化和线程的网站.它们都同时工作,但它们并不相互依赖.所以这意味着1个类 - 1个网站 - 1个线程.它不是特别优雅的解决方案,特别是对于管理代码,因为很多代码在每个类中重复(但不足以使它成为一个类来传递参数,因为一些站点可能需要在方法中间对检索到的数据进行额外处理 - 像'登录' - 其他人可能不需要).正如我所说,它并不优雅 - 但它有效.毋庸置疑,我欢迎所有建议如何更好地编写这个,而不使用每个网站方法的1个类.添加每个类的附加功能或整体代码管理是一项艰巨的任务.
但是,我发现,每个线程占用大约8MB内存,因此使用50个正在运行的线程,我们正在考虑大约400MB的使用量.如果它在我的系统上运行我就不会有问题,但由于它在仅有1GB内存的VPS上运行,因此它开始出现问题.你能告诉我如何减少内存使用量,还是有其他方法同时使用多个站点?
我使用这个快速测试python程序来测试它是存储在我的应用程序的变量中的数据是使用内存还是其他东西.正如您在下面的代码中看到的,它只处理sleep()函数,但每个线程使用8MB内存.
from thread import start_new_thread
from time import sleep
def sleeper():
try:
while 1:
sleep(10000)
except:
if running: raise
def test():
global running
n = 0
running = True
try:
while 1:
start_new_thread(sleeper, ())
n += 1
if not (n % 50):
print n
except Exception, e:
running = False
print 'Exception raised:', e
print 'Biggest number of threads:', n
if __name__ == '__main__':
test()
Run Code Online (Sandbox Code Playgroud)
当我运行它时,输出是:
50
100 …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个程序,以便与我创建的服务器建立大量的Web套接字连接:
class WebSocketClient():
@asyncio.coroutine
def run(self):
print(self.client_id, 'Connecting')
ws = yield from aiohttp.ws_connect(self.url)
print(self.client_id, 'Connected')
print(self.client_id, 'Sending the message')
ws.send_str(self.make_new_message())
while not ws.closed:
msg = yield from ws.receive()
if msg.tp == aiohttp.MsgType.text:
print(self.client_id, 'Received the echo')
yield from ws.close()
break
print(self.client_id, 'Closed')
@asyncio.coroutine
def make_clients():
for client_id in range(args.clients):
yield from WebSocketClient(client_id, WS_CHANNEL_URL.format(client_id=client_id)).run()
event_loop.run_until_complete(make_clients())
Run Code Online (Sandbox Code Playgroud)
问题是所有客户一个接一个地完成工作:
0 Connecting
0 Connected
0 Sending the message
0 Received the echo
0 Closed
1 Connecting
1 Connected
1 Sending the message
1 Received the …Run Code Online (Sandbox Code Playgroud) 我有一个python脚本,它会向各个域发出大量的HTTP和urllib请求.
我们有大量的域进程,需要尽快完成.由于HTTP请求很慢(即它们可能超出域上没有网站),我会在任何时候运行一些脚本,从数据库中的域列表中提取它们.
我看到的问题是在一段时间内(几小时到24小时)脚本都开始变慢,ps -al显示它们正在睡觉.
服务器功能非常强大(8核,72GB RAM,6TB Raid 6等80MB 2:1连接)并且永远不会超出,即Free -m显示
-/+ buffers/cache: 61157 11337
Swap: 4510 195 4315
Run Code Online (Sandbox Code Playgroud)
顶部显示80-90%闲置
sar -d显示平均5.3%的效用
更有趣的是,iptraf以大约50-60MB/s的速度开始,大约4小时后最终达到8-10MB/s.
我目前在每台服务器(2台服务器)上运行大约500个版本的脚本,它们都显示相同的问题.
ps -al 显示大多数python脚本正在睡觉,我不明白为什么例如:
0 S 0 28668 2987 0 80 0 - 71003 sk_wai pts/2 00:00:03 python
0 S 0 28669 2987 0 80 0 - 71619 inet_s pts/2 00:00:31 python
0 S 0 28670 2987 0 80 0 - 70947 sk_wai pts/2 00:00:07 python
0 S 0 28671 2987 0 80 0 - 71609 …Run Code Online (Sandbox Code Playgroud) python ×6
http ×2
python-3.x ×2
timeout ×2
aiohttp ×1
asynchronous ×1
concurrency ×1
linux ×1
linux-kernel ×1
performance ×1
sockets ×1
task ×1
unix ×1