Cannot import python mysql module when running script using crontab

I am using crontab to run a python script that requires a MySQLdb module. When I run this script from the command line, everything works fine. However, trying to start it with crontab raises 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 it to the top of my script #!/usr/bin/python . However, this did nothing, and I still get the same error. What am I doing wrong?

+8
source share
5 answers

You may be using a different Python executable. In the command 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 , and then in the first line of your script you should write:

 #!/home/myuser/bin/python 

It may also be that your shell has the PYTHONPATH environment variable. If this case and you find where it imports the library from, then you must add the path to search for the library in the first line of your script before importing "MySQLdb":

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

Define PYTHONPATH at the top of your crontab. Defining all of these environment variables (below) can help you avoid some of the common cron problems associated with missing 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 the path to MySQLdb, open the python shell and type:

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

Your path of mine is different. In the above example, the appropriate dir to add to PYTHONPATH would be /usr/lib/pymodules/python2.7 (although you do not need to add this specific path since your python executable should have this path in its sys.path automatically).

+6
source

The definition of PYTHONPATH inside crontab worked for me, first I entered crontab using:

 sudo crontab -e 

Then I added the library path to the PYTHONPATH variable. In my case, it was like this:

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

To find the library path, I first imported it with python and then used the file .

 import library library.__file__ 
+3
source

Try to run

 sudo -H pip install MySQLdb 

(note the -H option). I got a similar problem with another package

0
source

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

-1
source

Source: https://habr.com/ru/post/900545/


All Articles