我正在尝试从bash脚本运行python脚本,以使用crontab将文件上传到网站。该脚本从终端运行但不能从crontab运行,错误是
"Error: <urlopen error [Errno -2] Name or service not known>"
python脚本是: #!/ usr / bin / env python
from ConfigParser import ConfigParser
from mechanize import Browser, RobustFactory
import base64
from os.path import basename
import sys
import os
print(os.environ)
if __name__ == "__main__":
if len(sys.argv) != 2:
print "Error: 1 argument needed"
sys.exit(1)
#DATA FROM CFG FILE
url = "http:website"
cfn = "absolute_path/upload.cfg"
cfg = ConfigParser()
try:
cfg.read(cfn)
usr = cfg.get('Auth', 'user')
pwd = cfg.get('Auth', 'pass')
except Exception, e:
print "Error:", e
sys.exit(1)
if not usr or not pwd:
print "Error: username or password not valid."
sys.exit(1)
filename = sys.argv[1]
try:
br = Browser(factory=RobustFactory())
br.addheaders.append(('Authorization', 'Basic %s' % base64.encodestring('%s:%s' % (usr, pwd))))
br.open(url)
br.select_form(nr=1)
br.form.add_file(open(filename, 'rb'), 'text/plain', basename(filename))
br.submit()
print "File '%s' successfully uploaded" % filename
sys.exit(0)
except Exception, e:
print "Error:", e
sys.exit(1)
当我尝试在手动运行并使用crontab的情况下在python脚本中“打印(os.environ)”时:
使用crontab:
"{'MAILTO': '/var/mail/envclim', 'LANG': 'en_US.UTF-8', 'SHELL': '/bin/sh', 'XDG_RUNTIME_DIR': '/run/user/1000', 'SHLVL': '2', 'PYTHONPATH': '/usr/lib/python2.7/site-packages:/usr/lib/python2.7/site-packages/', 'OLDPWD': '/home/envclim/upload_sdswas', 'PWD': '/home/envclim/upload_sdswas/upload_scripts', 'LOGNAME': 'envclim', 'USER': 'envclim', 'HOME': '/home/envclim', 'PATH': '/bin:/usr/bin:/usr/local/bin:/usr/local/CDO/bin', 'XDG_SESSION_ID': '6', '_': '/usr/bin/python'}"
但在手动情况下,有代理,如下所示:
{'HTTP_PROXY': 'http://10.51.51.51:80/', 'KDE_IS_PRELINKED': '1', 'ALL_PROXY': 'socks://10.51.51.51:80/', 'NO_PROXY': 'localhost,127.0.0.0/8,::1', 'GJS_DEBUG_OUTPUT': 'stderr', 'http_proxy': 'http://10.51.51.51:80/', 'FTP_PROXY': 'http://10.51.51.51:80/',----------}
在crontab中,我添加:
SHELL=/bin/sh
PATH=/bin:/usr/bin
PYTHONPATH=/usr/lib/python2.7/site-packages
MAILTO=/var/mail/envclim
我正在使用fedora19。我试图禁用代理,但脚本根本不起作用。
请问,任何人都可以解决这个问题吗?提前致谢 泽纳布
答案 0 :(得分:1)
非常感谢您的评论,我通过添加以下几行解决了这个问题:
in crontab:
PYTHONPATH=/usr/lib/python2.7/site-packages
HTTP_PROXY=http://10.51.51.51:80/
and in bash file that used to run python script:
export PYTHONPATH=$PYTHONPATH:/usr/lib/python2.7/site-packages/
export LD_LIBRARY_PATH=/lib:/usr/lib:/usr/local/lib:/usr/local/usr/lib
I hope that be useful for someone
my best wishes
Zeinab