URLLib.Request 使用 cron 执行时返回连接超时 (CentOS)

URLLib.Request returning connection timout when executed with cron (CentOS)

我有一个 Python 脚本,我想每天使用 cron 执行它。我遇到问题的唯一脚本是使用 URLLib 请求的脚本,我收到连接超时错误:

回溯(最近调用最后):

  File "/usr/lib64/python3.6/urllib/request.py", line 1318, in do_open
    encode_chunked=req.has_header('Transfer-encoding'))
  File "/usr/lib64/python3.6/http/client.py", line 1254, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/usr/lib64/python3.6/http/client.py", line 1300, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/usr/lib64/python3.6/http/client.py", line 1249, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/usr/lib64/python3.6/http/client.py", line 1036, in _send_output
    self.send(msg)
  File "/usr/lib64/python3.6/http/client.py", line 974, in send
    self.connect()
  File "/usr/lib64/python3.6/http/client.py", line 1407, in connect
    super().connect()
  File "/usr/lib64/python3.6/http/client.py", line 946, in connect
    (self.host,self.port), self.timeout, self.source_address)
  File "/usr/lib64/python3.6/socket.py", line 724, in create_connection
    raise err
  File "/usr/lib64/python3.6/socket.py", line 713, in create_connection
    sock.connect(sa)
TimeoutError: [Errno 110] Connection timed out

这是 cron 执行:

0 3 * * * /usr/bin/python3.6 "/home/ngabioud/Scripts Python VM/ClickTableau.py"

您知道为什么这不起作用吗?如果我在命令行上手动 运行 该脚本工作正常。

谢谢!

这似乎是代理的问题。

here的回答为例,

事实证明,我必须设置代理设置,这样我才能以自己而不是 root 身份访问 AWS。我 运行 将 cron 作业作为 Linux shell 脚本而不是 Python 脚本,并导出了我的 http_proxy、https_proxy 和 no_proxy 设置在 ~/.bash_profile 中 shell 脚本的第一行

`export http_proxy=<http_proxy from ~/.bash_profile>
 export https_proxy=<https_proxy from ~/.bash_profile>
 export no_proxy=<no_proxy from ~./bash_profile>
 python <python script>`

如果您仍然无法对其进行排序,请说明您托管 cron-job 的位置以及以下步骤的输出。

考虑记录 cron-job stdout 和 stderr。这比 python 的错误跟踪更有帮助。

18 20 * * * python2.6 script.py > /test.log 2>/test.err &

还要检查 /var/log/messages 以获取任何信息。

最后,为什么不试试 celery 而不是 cron?参见 here