【发布时间】:2019-09-23 18:31:53
【问题描述】:
我已经多次 ping 了一个计算机列表,但是我第一次尝试使用 Python,其中包含大约 4,000 个计算机名称的列表,而且我的脚本非常慢。我将如何加快速度并将输出写入逗号分隔的文本文件?
import pandas as pd
import os
import sys
import subprocess
import datetime
#Get current date and time
now = datetime.datetime.now()
dt = now.strftime("%Y-%m-%d")
dtnow = now.strftime("%Y-%m-%d %H:%M")
#Open the file and read into memory
fh = pd.read_csv('list.csv')
#Fix column headers by replacing the spaces with a underscore
fh.columns = fh.columns.str.strip().str.replace(' ', '_')
#Read the computer names into a variable called "computers"
computers = fh.Machine_Name
#Debug - Uncomment line below to see a list of computer names from csv file
#print(computers)
def ping(comp):
args = ["ping", "-n", "2", comp]
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = p.communicate()
if 'bytes=32' in output:
writetofile(comp, ',online')
else:
writetofile(comp, ',offline')
#endIf
#endDef
def writetofile(compname, data):
with open('DLPProv_' + dt + '.txt', 'a') as f:
f.write(compname + data + '\n')
#endWith
#endDef
for i in computers:
ping(i)
#endFor
f.write('END: ' + dtnow)
f.close()
我尝试使用@rolandsmith 发布的代码,但出现错误:
import concurrent.futures as cf
import os
import pandas as pd
from pythonping import ping
#Open the file and read into memory
fh = pd.read_csv('list.csv')
#Fix column headers by replacing the spaces with a underscore
fh.columns = fh.columns.str.strip().str.replace(' ', '_')
#Read the computer names into a variable called "computers"
computers = fh.Machine_Name
def pingworker(address):
rv = ping(address, count=4)
if rv.success():
return address, True
return address,False
with cf.ThreadPoolExecutor() as tp:
res = tp.map(pingworker, computers)
【问题讨论】:
-
我认为
ping函数需要更多时间。是否可以在打印前后添加调试语句来计算所需时间? -
使用
concurrent.futures.ThreadPoolExecutor的map或multiprocessing.dummy.Pool的imap/imap_unordered来获得基于线程的并行性?这是此类延迟受限问题的常用解决方案。
标签: python python-3.x ping