python - Python - 如何将 Ping 结果输出到 Pandas DataFrame 对象
问题描述
这可能看起来微不足道,但我一直在研究如何将结果存储ping somedomain.com
到 Pandas Dataframe 对象中遇到障碍。
我尝试过使用pingparsing和pythonping等模块,但没有得到任何结果。
客观的:
硬编码 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.
解决方案
这是我对问题的解决方案:
# 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)
最初的“结果”变量如下所示
不需要那些花哨的库,os 库就可以了!
注意:此解决方案适用于 Windows,因为返回的 ping 次数始终为 4。
推荐阅读
- python - 如何使for循环中的语句超时
- ios - 如何将 UIImagePickerController 限制为仅选择纵向模式(深度效果)照片?
- python-3.x - 在 keras 回调中监控 F1 分数(或一般的自定义指标)
- c# - 如何将文件从 umbraco 后台上传到媒体部分?
- spring-kafka - Kafka Spring:如何为 ConcurrentKafkaListenerContainerFactory 和 ConcurrentMessageListenerContainer 编写单元测试?
- c++ - 为什么在尝试使用向量或映射来保持函数指针列表与 lambda 时出现编译错误
- suitescript2.0 - Suitescript 2.0 在不同线程上提交数据
- console - 在 Electron 中,我可以从主进程访问渲染器进程中的控制台吗
- javascript - Express/Node.js 页面刷新问题
- javascript - Javascript - 如何从对象数组字段评级中获得星级?