Speedtest python脚本

2024-04-27 15:28:37 发布

您现在位置:Python中文网/ 问答频道 /正文

您好,我是python新手,我正在尝试使用python从(speedtest.net)获取数据进行速度测试。我一直在寻找git集线器并找到speedtest cli。但它有很多我不需要的功能。我只想做一个简单的脚本,将运行3次。我发现了一些API,但我不知道如何将其修改为循环三次。任何帮助都将不胜感激。提前谢谢

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()

Tags: git功能脚本apigetnetcliserver
1条回答
网友
1楼 · 发布于 2024-04-27 15:28:37
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()

相关问题 更多 >