我有一个 Python 脚本,它通过 HTTP 下载 json 格式的数据。如果我使用请求模块通过命令行运行脚本,HTTP 连接成功并且数据下载没有任何问题。但是当我尝试将脚本作为 crontab 作业启动时,HTTP 连接会在一段时间后抛出超时。谁能告诉我这里发生了什么?我目前首先通过 bash 脚本下载数据,然后从该 bash 中运行 Python 脚本。但这是无稽之谈!非常感谢!
使用:3.6.1 |Anaconda 自定义(64 位)| (默认,2017 年 5 月 11 日,13:09:58)\n[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
P.S.:我还没有找到关于这个问题的任何帖子。如果在其他帖子上已经有这个问题的答案,那么请接受我的道歉。
这是我的代码的摘录。运行 requests.get(url) 时超时:
try:
response = requests.get(url)
messages = response.json()["Messages"]
except requests.exceptions.Timeout:
logging.critical("TIMEOUT received when connecting to HTTP server.")
except requests.exceptions.ConnectionError:
logging.critical("CONNECTION ERROR received when connecting to HTTP server.")
最佳答案
我刚刚找到了问题的答案。我已经定义了正在使用的代理,然后在我的代码中像这样使用它:
HTTP_PROXY="http://your_proxy:proxy_port"
PROXY_DICT={"http":HTTP_PROXY}
response = requests.get(url, proxies=PROXY_DICT)
引用:
Proxies with Python 'Requests' module
谢谢大家的理解。我想我应该在发布之前进行彻底的搜索。对不起。
关于linux - 通过 crontab 启动脚本时 Python 请求挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47101653/