Skip to content

Instantly share code, notes, and snippets.

@simonhearne
Last active February 3, 2024 17:54
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save simonhearne/eabf033bae8cee77972b9e96d2775eea to your computer and use it in GitHub Desktop.
Save simonhearne/eabf033bae8cee77972b9e96d2775eea to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import datetime
import speedtest
from influxdb import InfluxDBClient
# influx configuration - edit these
ifuser = "grafana"
ifpass = "<yourpassword>"
ifdb = "home"
ifhost = "127.0.0.1"
ifport = 8086
measurement_name = "speedtest"
# take a timestamp for this measurement
time = datetime.datetime.utcnow()
# run a single-threaded speedtest using default server
s = speedtest.Speedtest()
s.get_best_server()
s.download(threads=1)
s.upload(threads=1)
res = s.results.dict()
# format the data as a single measurement for influx
body = [
{
"measurement": measurement_name,
"time": time,
"fields": {
"download": res["download"],
"upload": res["upload"],
"ping": res["ping"]
}
}
]
# connect to influx
ifclient = InfluxDBClient(ifhost,ifport,ifuser,ifpass,ifdb)
# write the measurement
ifclient.write_points(body)
@aglerj
Copy link

aglerj commented May 23, 2020

for supporting python v3 I had to update this item #!/usr/bin/env python

to #!/usr/bin/env python3

maybe add a comment?

@j-n-s-k-n-r
Copy link

Hey,

i always get the following error when running the script. I run the script with sudo ./speedtest.py

Traceback (most recent call last):
  File "./speedtest.py", line 4, in <module>
    import speedtest
  File "/home/pi/speedtest.py", line 19, in <module>
    s = speedtest.Speedtest()
AttributeError: 'module' object has no attribute 'Speedtest'

I have followed the instructions so far.

My Python version is 2.7.16
Hardware: RPi 2 with Debian Buster

Cheers
Jonas

@matthuff20
Copy link

If I wanted to specify a server to use in the python script (an ID that shows from the 'speedtest-cli --list' command) - How would I go about adding that into the code?

@bhartsfield
Copy link

bhartsfield commented Aug 29, 2021

j-n-s-k-n-r, do not name your script the same name as an imported module. Otherwise, instead of importing the speedtest module, it will import the .py file.

In short, just name speedtest.py to something else.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment