Python将stdout写入日志文件

时间:2015-11-23 12:23:35

标签: python-2.7 subprocess ping

我需要使用ping cmd的输出创建一个csv文件,这样我就可以生成一个图形。但我怎么能做到平均。来自ping的响应时间是写在一个csv文件? (Excel)中

import subprocess

list_of_ips = ["facebook.com", "google.com"]
for ip in list_of_ips:
    ping_process = subprocess.Popen(['ping', '-c', '5', ip], stdout=subprocess.PIPE)
stdout = ping_process.stdout.read()

1 个答案:

答案 0 :(得分:0)

要将子进程'输出写入文件,请将文件对象作为stdout传递:

import subprocess

with open(ip + '--ping.log', 'wb', 0) as file:
    subprocess.call(['ping', ..., ip], stdout=file)

在您的情况下,您可能不希望按原样编写标准输出。要执行ICMP ping,如果您无法以管理员身份运行脚本,则必须使用外部setuid命令,例如pingping命令选项和输出可能因系统而异。在我的平台上,a regex suggested in this discussion works

#!/usr/bin/env python
import re
import sys
from subprocess import Popen, PIPE

avg_pattern = br"rtt min/avg/max/mdev = \d+.\d+/(\d+.\d+)/\d+.\d+/\d+.\d+"
for ip in sys.argv[1:]:
    p = Popen(['ping', '-c', '5', ip], stdout=PIPE)
    output = p.communicate()[0]
    avg_ms = float(re.search(avg_pattern, output).group(1))
    print("{ip},{avg_ms}".format(**vars()))

示例:

$ python -m avg_ping google.com facebook.com > avg-ping-time.csv

该命令运行avg_ping.py并将其输出写入avg-ping-time.csv文件。

无关:你可以并行发出ping请求:

#!/usr/bin/env python
import re
import sys
import subprocess
from multiprocessing.pool import ThreadPool

def ping(ip, pattern=br"rtt min/avg/max/mdev = \d+.\d+/(\d+.\d+)/\d+.\d+/\d+.\d+"):
    p = subprocess.Popen(['ping', '-c', '5', ip], stdout=subprocess.PIPE)
    return ip, float(re.search(pattern, p.communicate()[0]).group(1))

pool = ThreadPool(20)  # no more than 20 concurrent pings
for ip, avg_ms in pool.imap_unordered(ping, sys.argv[1:]):
    print("{ip},{avg_ms}".format(**vars()))

用法完全相同。