【问题标题】:latencies from a server using subprocess [closed]使用子进程的服务器延迟[关闭]
【发布时间】:2022-09-23 06:41:06
【问题描述】:

编写一个脚本以从谷歌服务器获取延迟并绘制延迟曲线(在 python 中)我附上了我的试用代码 到目前为止,这是代码:

import subprocess
from subprocess import check_output, Popen, call, PIPE, STDOUT

latency  = []
p = Popen(\'ping -n 10 google.com\', stdout = PIPE, stderr = STDOUT, shell = True)
for line in p.stdout:
    lntxt = line.decode(\'utf-8\').rstrip()
    words = lntxt.split(\' \')
    if words[0] == \'Reply\':
        print(lntxt)
        latency.append(words[4])
        
print(latency)

使用它的输出应该是这样的: Output

然后问题是用标题和轴绘制延迟曲线

  • 问题是什么?
  • 您在调用Popen() 时没有使用任何shell 功能,您应该传递一个列表[\'ping\', \'-n\', \'10\', \'google.com\'] 而没有shell=True
  • 欢迎来到 SO,我建议您编辑您的问题以说明该程序需要很长时间才能返回并最终打印 []。如果您描述尝试运行代码时发生的情况,您将获得更好的支持。

标签: python ping latency


【解决方案1】:

更新:改进了延迟捕获并添加了代码以将结果绘制为直方图。

import re
import subprocess

import matplotlib.pyplot as plt

n = 10  # Number of pings to run

""" Start ny pinging a Google name server and recording the ping
    latency in list "latency"
"""
latency  = []
#  Run the ping command in a subprocess
p = subprocess.run(['ping', '-n', str(n), '8.8.8.8'],
     capture_output=True, text=True)
# Split the response into lines
for line in p.stdout.split('\n'):
    # Detect and parse lines that start with "Reply"
    m = re.search('Reply.*time=(.*)ms', line )
    if m:
        # Remember the latency time.
        latency.append(int(m[1]))

print("latency", latency)


""" Now plot the result as a histogram
"""

# Create list "bins" like [... 5.5, 6.5, 7.5 ...]
xmin = min(latency)
xmax = max(latency)
bins = [x-.5 for x in range(xmin, xmax+2)]
print("bins:", bins)

# Create the gistogram
plt.hist(latency, bins)

# Find out the range of the y axis. The min will
# be 0 but the max will depend on the data
ax = plt.gca()
ymin, ymax = ax.get_ylim()
print(ymin, ymax)

# Set the x and y tick ranges
plt.xticks(range(xmin,xmax+2))
plt.yticks(range(int(ymin),int(ymax+1)))

# Finally add a title and x, y axis labels
plt.title('Google Ping Latency in Milliseconds')
plt.xlabel('Time (ms)')
plt.ylabel('Count')

plt.show()

输出:

latency [5, 6, 6, 6, 9, 9, 9, 12, 5, 14]
bins: [4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5]
ymin, ymax: 0.0 3.15

剧情:

【讨论】:

    猜你喜欢
    • 2021-08-25
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    相关资源
    最近更新 更多