Python speedtest.py从cron运行时无法连接到Internet



我有以下代码

#!/usr/bin/python3.8
import subprocess
import requests
import datetime
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
print("=============================================================");
now = datetime.datetime.now()
print(now);
# speedtest --single --json
speedout = subprocess.run(['speedtest', '--single', '--json'], stdout=subprocess.PIPE).stdout.decode('utf-8');
print("speedtest output:"+speedout);
now = datetime.datetime.now()
print(now);
print("=============================================================");

当我手动运行它时,它会生成以下日志

=============================================================
2021-04-26 12:23:14.869085
speedtest output:{"download": 48332978.441761896, "upload": 21216098.81470209, "ping": 43.796, "server": {"url": "http://hotcaldas.lampinc.com.br:8080/speedtest/upload.php", "lat": "-17.7450", "lon": "-48.6250", "name": "Caldas Novas", "country": "Brazil", "cc": "BR", "sponsor": "Hot Caldas Internet", "id": "40200", "host": "hotcaldas.lampinc.com.br:8080", "d": 230.63111881620188, "latency": 43.796}, "timestamp": "2021-04-26T15:23:15.343030Z", "bytes_sent": 26738688, "bytes_received": 60631816, "share": null, "client": {"ip": "179.xxx.xxx.14", "lat": "-1xxx", "lon": "-4xxx", "isp": "Vivo", "isprating": "3.7", "rating": "0", "ispdlavg": "0", "ispulavg": "0", "loggedin": "0", "country": "BR"}}
2021-04-26 12:23:39.011183
=============================================================

但当我把它放在crontab上(在我的帐户下(每小时运行时:

0 * * * *         /myscripts/monitors/speedtest.py >> /mylogs/speedtest.log 2>&1

它生成以下日志

ERROR: Unable to connect to servers to test latency.
=============================================================
2021-04-26 13:00:01.687964
speedtest output:
2021-04-26 13:00:13.539705
=============================================================

注意错误消息是如何在第一个========之前发生的

可能会发生什么?

更新。我把flush=True添加到所有打印中。它曾经奏效,但现在又失败了。现在错误消息更改了

=============================================================
2021-04-26 16:00:01.943727
ERROR: Unable to connect to servers to test latency.
speedtest output:
2021-04-26 16:00:03.616226
=============================================================

我以前也遇到过同样的问题。我将cron设置为每15分钟执行一次,在xx:00和xx:30的每个任务都失败了。也许speedtest有内部服务器问题。

因此,解决这个问题的方法是避免特定的时间。请试试这样的
5 * * * * /myscripts/monitors/speedtest.py >> /mylogs/speedtest.log 2>&1

最新更新