首页 > 解决方案 > Python - 如何将 Ping 结果输出到 Pandas DataFrame 对象

问题描述

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

我尝试过使用pingparsingpythonping等模块,但没有得到任何结果。

客观的:

硬编码 ping 目标(即:)将 ping 目标ping_target = 'google.com'的结果发送到数据框对象使用 pandas 提取数据(即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. 

标签: pythonpython-3.xpandasparsingping

解决方案


这是我对问题的解决方案:

# 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 结果

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


推荐阅读