Speedtest Python脚本

Alf*_*rre 0 python

您好,我是python的新手,我正尝试使用python从(speedtest.net)获取数据来进行速度测试。我一直在浏览git hub并找到speedtest-cli。但是它有很多我不需要的功能。我只想制作一个可以运行3次的简单脚本。我找到了一些API,但不确定如何将其修改为循环3次。任何帮助将不胜感激。提前致谢

import speedtest

servers = []
# If you want to test against a specific server
# servers = [1234]
x=0
for x in range(0, 2):
    s = speedtest.Speedtest()
    s.get_servers(servers)
    s.get_best_server()
    s.download()
    s.upload()
    s.results.share()
    results_dict = s.results.dict()
Run Code Online (Sandbox Code Playgroud)

Aiv*_*ven 7

import speedtest


def test():
    s = speedtest.Speedtest()
    s.get_servers()
    s.get_best_server()
    s.download()
    s.upload()
    res = s.results.dict()
    return res["download"], res["upload"], res["ping"]


def main():
    # write to csv
    with open('file.csv', 'w') as f:
        f.write('download,upload,ping\n')
        for i in range(3):
            print('Making test #{}'.format(i+1))
            d, u, p = test()
            f.write('{},{},{}\n'.format(d, u, p))
    # pretty write to txt file
    with open('file.txt', 'w') as f:
        for i in range(3):
            print('Making test #{}'.format(i+1))
            d, u, p = test()
            f.write('Test #{}\n'.format(i+1))
            f.write('Download: {:.2f} Kb/s\n'.format(d / 1024))
            f.write('Upload: {:.2f} Kb/s\n'.format(u / 1024))
            f.write('Ping: {}\n'.format(p))
    # simply print in needed format if you want to use pipe-style: python script.py > file
    for i in range(3):
        d, u, p = test()
        print('Test #{}\n'.format(i+1))
        print('Download: {:.2f} Kb/s\n'.format(d / 1024))
        print('Upload: {:.2f} Kb/s\n'.format(u / 1024))
        print('Ping: {}\n'.format(p))


if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)