简体   繁体   English

更改 speedtest.py 和 speedtest-cli 的 output 以将 IP 地址包含在 output.Z628Z19675FFE88FEF3F 文件中

[英]Changing output of speedtest.py and speedtest-cli to include IP address in output .csv file

I added a line in the python code “speedtest.py” that I found at pimylifeup.com.我在 pimylifeup.com 找到的 python 代码“speedtest.py”中添加了一行。 I hoped it would allow me to track the internet provider and IP address along with all the other speed information his code provides.我希望它能让我跟踪互联网提供商和 IP 地址以及他的代码提供的所有其他速度信息。 But when I execute it, the code only grabs the next word after the find all call.但是当我执行它时,代码只会在 find all 调用之后抓取下一个单词。 I would also like it to return the IP address that appears after the provider.我还希望它返回出现在提供程序之后的 IP 地址。 I have attached the code below.我附上了下面的代码。 Can you help me modify it to return what I am looking for.你能帮我修改它以返回我正在寻找的东西吗?

Here is an example what is returned by speedtest-cli这是 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
$

And this is an example of what it is being returned by speediest.py to my.csv file这是 speediest.py 返回到 my.csv 文件的示例

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

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

This is what I want it to return.这就是我希望它返回的内容。

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

Or may be,或者可能,

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

Here is the code that I am using.这是我正在使用的代码。 And thank you for any help you can provide.感谢您提供的任何帮助。

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))
$/usr/local/bin/speedtest-cli --csv-header > speedtestz.csv
$/usr/local/bin/speedtest-cli --csv >> speedtestz.csv

output: output:

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

Does that not get you what you're looking for?这不会让你得到你正在寻找的东西吗? Run the first command once to create the csv with header row.运行第一个命令一次以创建具有 header 行的 csv。 Then subsequent runs are done with the append '>>` operator, and that'll add a test result row each time you run it然后使用 append '>>` 运算符完成后续运行,每次运行时都会添加一个测试结果行

Doing all of those regexs will bite you if they or a library that they depend on decides to change their debugging output format如果他们或他们所依赖的库决定更改他们的调试 output 格式,那么执行所有这些正则表达式会咬你一口

Plenty of ways to do it though.有很多方法可以做到这一点。 Hope this helps希望这可以帮助

Let me know if this works for you, it should do everything you're looking for让我知道这是否适合您,它应该可以满足您的所有需求

#!/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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 创建一个python函数以在终端中运行speedtest-cli / ping并将结果输出到日志文件 - Create a python function to run speedtest-cli/ping in terminal and output result to a log file 不同界面上的 Speedtest-cli - Speedtest-cli on a different interface speedtest-cli 在控制台中工作,但不能作为脚本使用 - speedtest-cli works in console, but not as script 如何强制 python 调用 speedtest.py 使用安全服务器 - how to force python call to speedtest.py use secure servers 在 Python3 脚本中使用 speedtest-cli 来测量互联网速度 - 收到错误消息“No module named speedtest” - Using speedtest-cli within a Python3 script to measure internet speed - getting error message 'No module named speedtest' Python speedtest.py 从 cron 运行时无法连接到 Internet - Python speedtest.py failing to connect to Internet when run from cron Apache Airflow 给出损坏的 DAG 错误 cannot import __builtin__ for speedtest.py - Apache Airflow giving broken DAG error cannot import __builtin__ for speedtest.py 我如何在python脚本中使用speedtest-cli或任何替代方法而不是命令行? - How do i use speedtest-cli or any alternative in python script instead of command line? 有没有办法在速度测试期间使用 Python 的 speedtest-cli 库实时绘制实时下载/上传速度? - Is there a way to graph the real-time download/upload speed real time during a speed test using the speedtest-cli library for Python? python 'speedtest' 没有属性 'Speedtest' - python 'speedtest' has no attribute 'Speedtest'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM