1

我在 pimylifeup.com 上找到的 python 代码“speedtest.py”中添加了一行。我希望它能让我跟踪互联网提供商和 IP 地址以及他的代码提供的所有其他速度信息。但是当我执行它时,代码只会在 find all 调用之后抓取下一个单词。我还希望它返回出现在提供程序之后的 IP 地址。我附上了下面的代码。你能帮我修改它以返回我正在寻找的东西吗?

这是 speedtest-cli 返回的示例

$ speedtest-cli
Retrieving speedtest.net configuration...
Testing from Biglobe (111.111.111.111)...
Retrieving speedtest.net server list...
Selecting best server based on ping...
Hosted by GLBB Japan (Naha) [51.24 km]: 118.566 ms
Testing download speed................................................................................
Download: 4.00 Mbit/s
Testing upload speed......................................................................................................
Upload: 13.19 Mbit/s
$

这是 speediest.py 返回到我的 .csv 文件的示例

Date,Time,Ping,Download (Mbit/s),Upload(Mbit/s),myip

05/30/20,12:47,76.391,12.28,19.43,Biglobe

这就是我希望它返回的内容。

Date,Time,Ping,Download (Mbit/s),Upload (Mbit/s),myip

05/30/20,12:31,75.158,14.29,19.54,Biglobe 111.111.111.111

或者可能,

05/30/20,12:31,75.158,14.29,19.54,Biglobe,111.111.111.111

这是我正在使用的代码。感谢您提供的任何帮助。

import os
import re
import subprocess
import time

response = subprocess.Popen(‘/usr/local/bin/speedtest-cli’, shell=True, stdout=subprocess.PIPE).stdout.read().decode(‘utf-8’)

ping = re.findall(‘km]:\s(.*?)\s’, response, re.MULTILINE)
download = re.findall(‘Download:\s(.*?)\s’, response, re.MULTILINE)
upload = re.findall(‘Upload:\s(.*?)\s’, response, re.MULTILINE)
myip = re.findall(‘from\s(.*?)\s’, response, re.MULTILINE)

ping = ping[0].replace(‘,’, ‘.’)
download = download[0].replace(‘,’, ‘.’)
upload = upload[0].replace(‘,’, ‘.’)
myip = myip[0]

try:
f = open(‘/home/pi/speedtest/speedtestz.csv’, ‘a+’)
if os.stat(‘/home/pi/speedtest/speedtestz.csv’).st_size == 0:
f.write(‘Date,Time,Ping,Download (Mbit/s),Upload (Mbit/s),myip\r\n’)
except:
pass

f.write(‘{},{},{},{},{},{}\r\n’.format(time.strftime(‘%m/%d/%y’), time.strftime(‘%H:%M’), ping, download, upload, myip))
4

2 回答 2

1

让我知道这是否适合您,它应该可以满足您的所有需求

#!/usr/local/env python
import os
import csv
import time
import subprocess
from decimal import *

file_path = '/home/pi/speedtest/speedtestz.csv'

def format_speed(bits_string):
  """ changes string bit/s to megabits/s and rounds to two decimal places """
  return (Decimal(bits_string) / 1000000).quantize(Decimal('.01'), rounding=ROUND_UP)

def write_csv(row):
  """ writes a header row if one does not exist and test result row """
  # straight from csv man page
  # see: https://docs.python.org/3/library/csv.html
  with open(file_path, 'a+', newline='') as csvfile:
    writer = csv.writer(csvfile, delimiter=',', quotechar='"')

    if os.stat(file_path).st_size == 0:
      writer.writerow(['Date','Time','Ping','Download (Mbit/s)','Upload (Mbit/s)','myip'])

    writer.writerow(row)


response = subprocess.run(['/usr/local/bin/speedtest-cli', '--csv'], capture_output=True, encoding='utf-8')

# if speedtest-cli exited with no errors / ran successfully
if response.returncode == 0:

  # from the csv man page
  # "And while the module doesn’t directly support parsing strings, it can easily be done"
  # this will remove quotes and spaces vs doing a string split on ','
  # csv.reader returns an iterator, so we turn that into a list
  cols = list(csv.reader([response.stdout]))[0]

  # turns 13.45 ping to 13
  ping = Decimal(cols[5]).quantize(Decimal('1.'))

  # speedtest-cli --csv returns speed in bits/s, convert to bytes
  download = format_speed(cols[6])
  upload = format_speed(cols[7])

  ip = cols[9]

  date = time.strftime('%m/%d/%y')
  time = time.strftime('%H:%M')

  write_csv([date,time,ping,download,upload,ip])

else:
  print('speedtest-cli returned error: %s' % response.stderr)

于 2020-06-18T08:41:43.073 回答
0
$/usr/local/bin/speedtest-cli --csv-header > speedtestz.csv
$/usr/local/bin/speedtest-cli --csv >> speedtestz.csv

输出:

Server ID,Sponsor,Server Name,Timestamp,Distance,Ping,Download,Upload,Share,IP Address

这不会让你得到你正在寻找的东西吗?运行第一个命令一次以创建带有标题行的 csv。然后使用 append '>>` 运算符完成后续运行,每次运行时都会添加一个测试结果行

如果它们或它们所依赖的库决定更改它们的调试输出格式,那么执行所有这些正则表达式会咬你一口

有很多方法可以做到这一点。希望这可以帮助

于 2020-05-30T06:43:28.423 回答