Python-如何将Ping结果输出到Pandas DataFrame对象

问题描述

这看似微不足道,但我一直在研究如何将ping somedomain.com的结果存储到Pandas Dataframe对象中遇到障碍。

我曾尝试使用 pingparsing pythonping 之类的模块,但没有成功。

目标:

对ping目标进行硬编码(即:ping_target = 'google.com') 将ping目标的结果发送到数据框对象 使用熊猫提取数据(即pd.describe(ping_results)

我尝试过的

import pingparsing
import json
import numpy as np
import pandas as pd
from textwrap import dedent

parser = pingparsing.PingParsing()

ping_parser = pingparsing.PingParsing()
transmitter = pingparsing.PingTransmitter()
transmitter.destination = "google.com"
transmitter.count = 10
result = transmitter.ping()
stats = parser.parse(dedent(result))

# This "should" return each icmp_reply from the stats object.                     
for icmp_reply in stats.icmp_replies:
    print(icmp_reply)

错误

<ipython-input-36-b7c7a41d50df> in <module>
     14 transmitter.count = 10
     15 result = transmitter.ping()
---> 16 stats = parser.parse(dedent(result))
     17 
     18 

C:\ProgramData\Anaconda3\lib\textwrap.py in dedent(text)
    428     # all lines.
    429     margin = None
--> 430     text = _whitespace_only_re.sub('',text)
    431     indents = _leading_whitespace_re.findall(text)
    432     for indent in indents:

TypeError: expected string or bytes-like object```
## Note
I'm not stuck on using this pingparsing module and would prefer a more organic way using python stdout but want to see if this can be possible without parsing heavily using regex. Ideally I'd want to use as much vanilla python or builtins before converting output to dataframe. 

解决方法

这是我解决该问题的方法:

# Import packages
import os
import pandas as pd
import numpy as np

# Define ping target,ping the target,and then store results as string
ping_target = 'google.com'
results = os.popen('ping ' + ping_target).read()
print(results)

# Extract the times from the results string
times = []
for i in range(4):
    timeIdx = results.index('time')
    time = results[timeIdx+5:timeIdx+7]
    
    results = results[timeIdx+10:]
    
    times.append(time)
    
# Put data into pandas DataFrame
d = {'PingNum': np.arange(1,5),'PingTime_ms': times}
df = pd.DataFrame(data=d)

初始的“结果”变量如下所示:

Ping results

不需要那些精美的库,os库就可以了!
注意:此解决方案适用于Windows,因为返回的ping次数始终为4。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...