Cannot Import Python MySQL module when running a script using crontab

允我心安 提交于 2019-11-29 08:30:18

问题


I am using crontab to run a python script that requires the module MySQLdb. When I run this script from the command line everything works fine. However, trying to run it using crontab elicits this error.

Traceback (most recent call last):
  File "clickout.py", line 3, in <module>
    import MySQLdb
ImportError: No module named MySQLdb

I did a google search and added this to the top of my script #!/usr/bin/python. However, this didn't do anything and I am still getting the same error. What am I doing wrong?


回答1:


It may be that you're using a different Python executable. On the shell, enter which python to find out where the Python executable is located. Let's say this returns something other than /usr/bin/python, say /home/myuser/bin/python, then in the first line of your script, you would write:

#!/home/myuser/bin/python

It may also be that your shell has environment variable called PYTHONPATH. If that's the case and you find where it's importing the library from, then this is how you would add the path to find the library in the first line of your script, before the import of "MySQLdb":

import sys; sys.path.append('/path/to/MySQLdb-lib/')



回答2:


Define PYTHONPATH at the top of your crontab. Defining all these environment variables (below) can help you avoid some common cron problems relating to the lack of environment variables:

USER=...
HOME=/home/...
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin:$HOME/bin
PYTHONPATH=...
DISPLAY=:0.0
MAILTO=...
LANG=en_US.UTF-8

To find out the path to MySQLdb, open a python shell and type:

>>> import MySQLdb
>>> MySQLdb.__file__
'/usr/lib/pymodules/python2.7/MySQLdb/__init__.pyc'

Your path my differ. In the example above, the appropriate dir to add to PYTHONPATH would be /usr/lib/pymodules/python2.7 (though you should not have to add this particular path since your python executable should have this path in its sys.path automatically).




回答3:


Defining the PYTHONPATH inside crontab worked for me, first I entered crontab using:

sudo crontab -e

I then added the libraries path to the PYTHONPATH variable. In my case it was this:

PYTHONPATH=/home/username/.local/lib/python2.7/site-packages

To find the path of the library I first imported it using python and then used the file attribute.

import library
library.__file__



回答4:


Try running

sudo -H pip install MySQLdb

(note the -H option). It worked for me with a similar issue with another package




回答5:


The problem is that this module is not in the python module search path of the crontab user. Try looking here: http://docs.python.org/tutorial/modules.html#the-module-search-path



来源:https://stackoverflow.com/questions/7970905/cannot-import-python-mysql-module-when-running-a-script-using-crontab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!