Cannot Import Python MySQL module when running a script using crontab

Spencer picture Spencer · Nov 1, 2011 · Viewed 17k times · Source

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?

Answer

Daniel Nouri picture Daniel Nouri · Nov 1, 2011

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/')