Python 将标准输出写入日志文件

Python write stdout to log file

我需要使用 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()

您可以尝试使用正则表达式处理您在标准输出中获得的响应并获得您的平均时间。或者您可以使用 python 模块并像本帖 Ping a site in Python?

中描述的那样自己完成

编辑: 最简单的方法是使用正则表达式。我已经稍微修改了您的代码片段:

import subprocess, re

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()
    match = re.search(r'\d*\.\d*\/(\d*\.\d*)\/\d*\.\d*\/\d*\.\d*', stdout)
    avg = match.group(1)
    print('{}: {}ms'.format(ip, avg))

编辑2: 好的,现在应该合适了 ;)

import subprocess, re, csv

list_of_ips = ["facebook.com", "google.com"]
avgTimeList = []
for ip in list_of_ips:
    ping_process = subprocess.Popen(['ping', '-c', '5', ip], stdout=subprocess.PIPE)
    stdout = ping_process.stdout.read()
    match = re.search(r'\d*\.\d*\/(\d*\.\d*)\/\d*\.\d*\/\d*\.\d*', stdout)
    avg = match.group(1)
    avgTimeList.append([ip, avg])

with open('avgTimes.csv', 'w') as csvfile:
    csvWriter = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
    for data in avgTimeList:
        csvWriter.writerow(data)

要将子进程的输出写入文件,将文件对象作为标准输出传递:

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

命令 运行s 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()))

用法完全一样