【发布时间】:2021-07-20 00:49:43
【问题描述】:
我有以下代码
#!/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
=============================================================
【问题讨论】:
-
您打算在虚拟环境中运行吗?
-
不,它在我的本地服务器上运行。我打算将它的输出存储在一个变量中并将其发送到一个 Web 服务,在那里我提取一些数据并存储在 Postgres 上。
-
请将
flush=true添加到您的打印件中.. -
如果你以root身份运行
speedtest.py,是否成功? -
它似乎与flush = True一起使用。我减少到 15 分钟以进行更多测试。 print 是否有任何理由影响 subprocess.run()?在没有打印之前,我添加了它来制作日志,因为我在 DB 上什么也没得到。
标签: python python-3.x python-3.8 speed-test