我想在一个带有gevent的文件中跟踪一些ip,这是我的代码:
#!/usr/bin/env python
import gevent
from gevent import subprocess
gevent.monkey.patch_thread
ip_list = open('ips.txt')
data = [i for i in ip_list]
length = len(data)
process_pool = []
for i in range(length):
process = subprocess.Popen(['sudo','traceroute','-T', '-m', '8', data[i]], stdout=subprocess.PIPE)
process_pool.append(process)
print len(process_pool)
gevent.wait(process_pool, timeout=10)
count = 0
for i in process_pool:
if i.poll() is not None:
count += 1
print i.stdout.read()
else:
print ('job is still running')
print count
它运行良好,但我不知道如何更改超时值,如何查看所有traceroute是否结束。所有过程都可能结束,但我不知道文件中有多少ip,因此代码无法处理常见情况。怎么解决?
答案 0 :(得分:1)
事实上,我只想使用gevent来查看代码的速度,所以我可以使用这样的代码,它对我的工作来说足够快:
#!/usr/bin/python
import gevent
from gevent import monkey, subprocess
gevent.monkey.patch_thread
all_data = []
def my_trace(ip_addr):
process = subprocess.Popen(['sudo','traceroute','-T','-m','8', ip_addr], stdout=subprocess.PIPE)
all_data.append(process.stdout.read())
ip_list = open('ips.txt')
data = [i for i in ip_list]
jobs = [gevent.spawn(my_trace, line) for line in data]
gevent.wait(jobs)
for i in all_data:
print i
print len(all_data)
而且,我只是等待所有的traceroute结束,就是这样。