如果我独立运行程序,Urllib2 运行良好,但是当我将它添加到 cronjob 时抛出错误 [英] Urllib2 runs fine if i run the program independently but throws error when i add it to a cronjob

查看:59
本文介绍了如果我独立运行程序,Urllib2 运行良好,但是当我将它添加到 cronjob 时抛出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<前>url = "www.someurl.com"request = urllib2.Request(url,header={"User-agent" : "Mozilla/5.0"})contentString = urllib2.url(request).read()contentFile = StringIO.StringIO(contentString)对于范围内的 i (0,2):html = contentFile.readline()打印html

上述代码在命令行中运行良好,但如果我将其添加到 cron 作业中,则会引发以下错误:

 文件/usr/lib64/python2.6/urllib2.py",第 409 行,在 _open'_open',请求)_call_chain 中的文件/usr/lib64/python2.6/urllib2.py",第 369 行结果 = func(*args)文件/usr/lib64/python2.6/urllib2.py",第 1186 行,在 http_open返回 self.do_open(httplib.HTTPConnection, req)文件/usr/lib64/python2.6/urllib2.py",第 1161 行,在 do_open 中引发 URLError(err)urllib2.URLError:

我确实在其他论坛上看过一些提示并尝试过,但没有用.

任何帮助将不胜感激.

解决方案

crontab 和命令行使用的环境变量不同.

我通过添加 */15 * * * * 解决了这个问题.$HOME/.profile;/路径/到/命令.

这使得 crontab 选择为系统指定的环境变量.

url = "www.someurl.com"

request = urllib2.Request(url,header={"User-agent" : "Mozilla/5.0"})

contentString = urllib2.url(request).read()

contentFile = StringIO.StringIO(contentString)

for i in range(0,2):
    html = contentFile.readline()

print html

The above code runs fine from commandline but if i add it to a cron job it throws the following error:

  File "/usr/lib64/python2.6/urllib2.py", line 409, in _open
    '_open', req)
  File "/usr/lib64/python2.6/urllib2.py", line 369, in _call_chain
    result = func(*args)
  File "/usr/lib64/python2.6/urllib2.py", line 1186, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "/usr/lib64/python2.6/urllib2.py", line 1161, in do_open
    raise URLError(err)
urllib2.URLError: 

I did look at some tips on the other forums and tried it but it has been of no use.

Any help will be much appreciated.

解决方案

The environment variables that were used by crontab and from the command line were different.

I fixed this by adding */15 * * * * . $HOME/.profile; /path/to/command.

This made the crontab to pick up enivronment variables that were specified for the system.

这篇关于如果我独立运行程序,Urllib2 运行良好,但是当我将它添加到 cronjob 时抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆