将一個python腳本放入crontab執行時,提示如下錯:
ImportError: No module named hashlib
但是在shell中直接執行時沒有任何問題,google之後,得到線索是PYTHONPATH的問題,PYTHONPATH會決定python查找lib的路徑。
在伺服器上面echo $PYTHONPATH的時候沒有任何路徑
繼續調查發現最終影響的是sys.path
分别輸出了兩種場景中的sys.path
shell:
[root@ short_task]# python
Python 2.6.2 (r262:71600, Aug 7 2009, 18:39:16)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print sys.path
['', '/usr/local/lib/python2.6/site-packages/setuptools-0.6c5-py2.6.egg', '/usr/local/lib/python2.6/site-packages/MySQL_python-1.2.2-py2.6-linux-x86_64.egg', '/home/houjw/short_task', '/home/bonny/sqlLib', '/usr/local/lib/python26.zip', '/usr/local/lib/python2.6', '/usr/local/lib/python2.6/plat-linux2', '/usr/local/lib/python2.6/lib-tk', '/usr/local/lib/python2.6/lib-old', '/usr/local/lib/python2.6/lib-dynload', '/usr/local/lib/python2.6/site-packages']
crontab:
于是修改腳本,檢視當腳本在crontab執行時的syspath是多少
[root@ short_task]# less get_email_hash.log
['/home/houjw/short_task', '/usr/lib64/python24.zip', '/usr/lib64/python2.4', '/usr/lib64/python2.4/plat-linux2', '/usr/lib64/python2.4/lib-tk', '/usr/lib64/python2.4/lib-dynloa
d', '/usr/lib64/python2.4/site-packages', '/usr/lib64/python2.4/site-packages/Numeric', '/usr/lib64/python2.4/site-packages/gtk-2.0', '/usr/lib/python2.4/site-packages']
Traceback (most recent call last):
File "/home/houjw/short_task/get_email_hash.py", line 7, in ?
import hashlib
然後研究了一下sys.patch的生成方式:
A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.
這個不僅與PYTHONPATH有關系,而且與installation-dependent default有關系,這個估計與python的安裝有關系,而且通過上面的sys.path輸出發現機器上安裝了兩個python2.4和2.6,說明crontab中用到的是2.4,而shell中用到的是2.6,hashlib正好是在2.5的時候加入python的,是以2.4就沒有找到。
通過cat crontab發現crontab中的PATH變量首先發現的是2.4的python
于是問題就得到了解決,在crontab中使用/usr/loca/bin/python XXX.python而不是python XXX.python或者将XXX.python修改為可執行檔案,在python頭部#!/usr/local/bin/python