Spencer Spencer - 1 year ago 161
Python Question

Cannot Import Python MySQL module when running a script using crontab

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
. However, this didn't do anything and I am still getting the same error. What am I doing wrong?

Answer Source

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:


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/')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download