I have a simple Python script that I am trying to setup as a cron job, but it refuses to run. It does run when I run it by itself calling it as:
python script.py
I have tried setting my evironment variables in the crontab, but I cant get it to work. My crontab looks like this:
# For more information see the manual pages of crontab(5) and cron(8)
# m h dom mon dow command
SHELL=/bin/bash
PATH=/home/netadmin/bin:/home/net/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/b$
*/2 * * * * PYTHONPATH=/user/bin/python /home/net/path-to-script/script.py >>/home/net/out.txt 2>&1
Any Ideas on this?
4 Answers 4
You are mixing up two unrelated concepts:
- the Python interpreter location, which is the path to the Python interpreter program (an executable file somewhere)
- and the PYTHONPATH, which is a string indicating search locations (directories) for Python libraries. It is not the location of the Python interpreter, but rater a
:-separated list of directories. If you don't know what it's useful for, don't use it!
If doing python script.py works, there is generally no need to tweak the PYTHONPATH. You can obtain the full path to the Python interpreter with which:
$ which python
/usr/bin/python
This will print the absolute path to the Python interpreter that you can use in your crontab:
*/2 * * * * /usr/bin/python /path/to/script.py >>/home/net/out.txt 2>&1
Don't tweak PYTHONPATH if you don't need to. If script.py relies on libraries that are not installed on the system, I encourage you to learn & use virtualenvs. It's easy and solves most Python library dependency issues.
Comments
You can create a shell script (we'll call it foo.sh for this example) which would look like this:
#! /bin/bash
/user/bin/python /home/net/path-to-script/script.py >>/home/net/out.txt 2>&1
You need to make foo.sh executable, so you will need to run the following to do that:
chmod +x /home/net/path-to-script/foo.sh
Finally, you can add the shell script to a cron job by running this (which you seem familiar with):
crontab -e
Add a line as follows:
*/2 * * * * /home/net/path-to-script/foo.sh
That should do it, good luck!
Comments
Why are you setting environment variable PYTHONPATH, you can run it directly also I believe path for python would be usr instead of user try this
*/2 * * * * cd /home/net/path-to-script ; /usr/bin/python script.py >>/home/net/out.txt 2>&1
Comments
This line is incorrect, remove PYTHONPATH
*/2 * * * * PYTHONPATH=/usr/bin/python /home/net/path-to-script/script.py >>/home/net/out.txt 2>&1
=>
*/2 * * * * /usr/bin/python /home/net/path-to-script/script.py >>/home/net/out.txt 2>&1
It's recommended to use Shebang however.
.sha script that will make everything and run it from cron. I make so. It's much easy.sha script that will do all as you do incrontab. You can test this script and all is ok - just add it to your cron job