我有一个用 python 编写的非常简单的脚本,用于测试我的互联网连接,并将解析的数据保存到 json 文件中:
#!/usr/bin/python3
import subprocess, json, os
from datetime import datetime
# run the bash script and parse results
def speedtest():
result = subprocess.run(["/bin/speedtest-cli", "--simple"], stdout=subprocess.PIPE, encoding="UTF-8").stdout
# result = os.system("speedtest-cli --simple")
download_str = result.find("Download: ") + 10
download_speed = result[download_str:result.find(" Mbit/s", download_str)]
upload_str = result.find("Upload: ") + 8
upload_speed = result[upload_str:result.find(" Mbit/s", upload_str)]
ping_str = result.find("Ping: ") + 6
ping = result[ping_str:result.find(" ms", ping_str)]
return download_speed, upload_speed, ping
def save_to_json(data):
# load existing data to a dict
existing_data = []
with open("/home/trendkiller/development/python/py_speedtest/data.json") as fp:
existing_data = json.load(fp)
payload = {
"date": datetime.now().strftime("%d/%m/%Y"),
"time": datetime.now().strftime("%H:%M"),
"download": data[0] + " Mbps",
"upload": data[1] + " Mbps",
"ping": data[2] + " ms"
}
existing_data.append(payload)
# save to a json file
with open("/home/trendkiller/development/python/py_speedtest/data.json", "w") as f:
json.dump(existing_data, f, indent=4)
def main():
test_result = speedtest()
# save to a json_file
save_to_json(test_result)
return 0
if __name__ == "__main__":
main()
当我从终端调用它时,它运行顺利。 我想将其自动化,以便它可以每小时测试我的连接。 为此,我尝试使用 CRON,当我安排它每分钟运行一次时(数据保存到 data.json),它就可以工作。 但是当我尝试每小时运行一次时,数据不会传递到 json 文件。 这是我的 crontab 文件:
@hourly /bin/python3 /home/trendkiller/python/py_speedtest/main.py
提前致谢(不要介意混乱的代码:P)。
如果代码有效,则意味着您的 cron 可能有问题,所以我建议:
@hourly /bin/python3 /home/trendkiller/python/py_speedtest/main.py >> /home/trendkiller/python/py_speedtest/cron.log 2>&1
50 14 * * * /bin/python3 /home/trendkiller/python/py_speedtest/main.py >> /home/trendkiller/python/py_speedtest/cron.log 2>&1