speedtest-cli works in console, but not as script

Question:

I am trying to use the speedtest-cli api. Copied part of the code from official wiki (and removed unused stuff):

import speedtest
s = speedtest.Speedtest()
s.get_best_server()
s.download()

In python console I get everything ok:

>>> import speedtest
>>> s = speedtest.Speedtest()
>>> s.get_best_server()
{HIDDEN}
>>> s.download()
37257579.09084724

But when I create .py file and run it I get:

AttributeError: module 'speedtest' has no attribute 'SpeedTest'

Thanks

Asked By: Makalone LOgman

||

Answers:

As mentioned in the comments, you have a file with the same name and it is conflicting with the import. Since you have moved the file, restarting the console should work.

The code below will also extract the results into a dictionary and make it possible to access the results.

import speedtest
s = speedtest.Speedtest()
s.get_best_server()
s.download()
s.upload()
res = s.results.dict()
print(res["download"], res["upload"], res["ping"])
Answered By: mirmo

Try checking speedtest is imported properly

import speedtest
print(dir(speedtest))

it should display properties of speedtest

Answered By: Nishan B

I faced the same issue because I had installed both speedtest and speedtest-cli.
Using pip uninstall speedtest worked for me.

Answered By: Suyash Misra

I faced the same issue because the name of my file was speedtest. When I change the name to something new. It works fine for me.

import speedtest
wifi  = speedtest.Speedtest()
print("Wifi Download Speed is ", wifi.download())
print("Wifi Upload Speed is ", wifi.upload())
Answered By: Zaheer Khan Niazi

Ok Here is the Solution to this Problem

1-uninstall speedtest and speedtest-cli if you have both installed

2- install only speedtest-cli pip install speedtest-cli this will install the package in the main python environment

3-CTRL+P select interpreter then select your main python not any environment

4-it will work fine

Reason for this error

(you install the package in your main python environment and you usually open your IDE and run a virtual environment)

Answered By: Mohamed Fathallah
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.