I'm just setting up a cron tab/job on my Cent OS developement server.
Within my crontab I have the following. (Ignore the time setting, this was added about 15:32 UTC server time just to get the next scheduled run in).
34 15 * * * cd welcomeclient-0.0.5 && python3.6 main.py
In the command line cd welcomeclient-0.0.5 && python3.6 main.py works fine. welcomeclient-0.0.5 is under root in the droplet, and python3.6 is in /usr/bin.
Any suggestions?
Try using absolute paths in your crontab command:
34 15 * * * cd /foo/bar/welcomeclient-0.0.5 && /usr/bin/python3.6 main.py
or, assuming the main.py does not also make use of relative paths inside of it :
34 15 * * */usr/bin/python3.6 /foo/bar/welcomeclient-0.0.5/main.py
Looks like you're trying to change directory in crontab, just like omu_negru said you'll need to use full path instead. That's because crontab even if running under your name will not inherit your environmental variables such as $PATH.
Try this. First, go to the directory where your script is... and turn your main.py to an executable file so you don't have to call python main.py anymore. The simplest way to do so is...
$ chmod u+x main.py
Now if you do ls -l you'll see that you have "x" in the user section of permissions which will allow you to run it directly.
-rwxr--r-- 1 user user 0 Aug 17 17:55 main.py
Now you're ready to simplify crontab syntax to something like this...
34 15 * * * /foo/bar/welcomeclient-0.0.5/main.py
I also like to capture the output from the script to a log file so it's easier to troubleshoot when things don't work our as planned, as follows:
34 15 * * * /foo/bar/welcomeclient-0.0.5/main.py & >> /foo/bar/main.log
The log should be added to log rotation, otherwise it will keep filling up and eventually make your system run out of space, but that's another topic already addressed on this site.
I have a simple Python script on EC2 to write a text to a file:
with open("/home/ec2-user/python/test.txt", "a") as f:
f.write("test\n\n")
That python script is here:
/home/ec2-user/python/write_file.py
When I run that script manually ('python /home/ec2-user/python/write_file.py') - new text is being written to a file ('/home/ec2-user/python/test.txt').
When schedule same script using Cronjob - no data is being added to a file. My Cronjob looks like this:
* * * * * python /home/ec2-user/python/write_file.py
I verify Cronjob is running and suspecting some ENV parameters are not the same during Cronjob execution (or something else is happening). What could be the case and how to fix it in a simple way?
Thanks.
I recently began using Amazon's linux distro on ec2 instances and after trying all kinds of things for cron all I needed was:
sudo service crond start
crontab -e
This allowed me to set a cron job as "ec2-user" without specifying the user or env variables or anything. For example, this single line worked:
0 12 * * * python3 /home/ec2-user/example.py
I also posted this here.
On crontab
HOME=/home/ec2-user/
* * * * * python /home/ec2-user/python/write_file.py
alternatively (testing purpose)
* * * * * root /home/ec2-user/python/write_file.py
On your write_file.py add shebang (first line)
#!/usr/bin/env python
BONUS: (feel free to ignore) my first response debug method for cron on minute tasks:
import os
while True:
print os.popen('pgrep -lf python').read()
executed from shell will pop out all python modules called by cron. After 60 secs you know whats going on.
it's bette to specify the absolute path of the python interpreter because the command may not be recognized by the system. Or you can add the shebang line to your script #!pathToPythonInterpreter at the first line of your script
make sure that the user who planning the execution of script have the right to read and write to the file
make sure that you are not using the system corntab /etc/crontab to planify because then you have to specify the user who will execute the command.
I hope that this will help you
I have a python script I want to fire off every night at midnight. I'm using cron scheduler right now to do so, however, I can't figure out why it's not working. For now, I've been using close times (within the next minute or so) to test the cronjob, but I will ultimately want it to work for midnight.
Here is what I put in my crontab file (to run for 2:43pm), hosted on my ubuntu machine:
43 14 * * * root /home/grantmcgovern/Developer/Projects/StudyBug/Main.py
I even put the:
#!user/bin/python
on top of all the .py files.
I also did:
chmod +x "scriptname".py
For each of the .py files and still no luck. Am I missing something blatantly obvious? I should note, this is my first time playing with cron tasks.
From your current crontab file, you're basically running root /home/grantmcgovern/Developer/Projects/StudyBug/Main.py every time.
If you want to run it as root, use sudo crontab -e and put 43 14 * * * /usr/bin/python /home/grantmcgovern/Developer/Projects/StudyBug/Main.py instead.
I think it is looking for the command "root" so the syntax is wrong, so it should be this...
43 14 * * * /home/grantmcgovern/Developer/Projects/StudyBug/Main.py
If you need it to run as root then I think you can use su like this:
43 14 * * * su root -c "/home/grantmcgovern/Developer/Projects/StudyBug/Main.py"
If you add it to the system crontab then I think it will anyway.
crontab fails to execute a Python script. The command line I am using to run the Python script is ok.
These are solutions I had tried:
add #!/usr/bin/env python at the top of the main.py
add PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin at the top of crontab
chmod 777 to the main.py file
service cron restart
my crontab is:
PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
*/1 * * * * python /home/python_prj/main.py
and the log in /var/log/syslog is:
Nov 6 07:08:01 localhost CRON[28146]: (root) CMD (python /home/python_prj/main.py)
and nothing else.
The main.py script calls some methods from other modules under python_prj, does that matter?
Anyone can help me?
The main.py script calls some methods from other modules under python_prj, does that matter?
Yes, it does. All modules need to be findable at run time. You can accomplish this in several ways, but the most appropriate might be to set the PYTHONPATH variable in your crontab.
You might also want to set the MAILTO variable in crontab so you get emails with any tracebacks.
[update] here is the top of my crontab:
www:~# crontab -l
DJANGO_SETTINGS_MODULE=djangocron.settings
PATH=...
PYTHONPATH=/home/django
MAILTO="cron-notices#example.com"
...
# m h dom mon dow command
10-50/10 * * * * /home/django/cleanup_actions.py
...
(running cleanup actions every 10 minutes, except at the top of the hour).
Any file access in your scripts? And if so, have you used relative paths (or even: no explicit path) in your script?
When run from commandline, the actual folder is 'your path', where you start the script from. When run by cron, 'your path' may be different depending on environment variables.
So try using absolute paths to any files you access.
Check the permissions of the script. Make sure that it's executable by cron-- try chmod +x main.py.
This question already has answers here:
CronJob not running
(19 answers)
Closed 2 years ago.
My python script is not running under my crontab.
I have placed this in the python script at the top:
#!/usr/bin/python
I have tried doing this:
chmod a+x myscript.py
Added to my crontab -e:
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=""
* * * * * /home/me/project/myscript.py
My /var/log/cron file says:
Sep 21 11:53:02 163-dhcp /USR/SBIN/CROND[2489]: (me) CMD (/home/me/project/myscript.py)
But my script is not running because when I check my sql database, nothing has changed. If I run it directly in the terminal like so:
python /home/me/project/myscript.py
I get the correct result.
This is the myscript.py:
#!/usr/bin/python
import sqlite3
def main():
con = sqlite3.connect("test.db")
with con:
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS testtable(Id INTEGER PRIMARY KEY, Name TEXT)")
cur.execute("INSERT INTO testtable(Name) VALUES ('BoB')")
cur.execute("SELECT * FROM testtable")
print cur.fetchall()
if __name__ == "__main__":
main()
Per comments: Yes, /usr/bin/python exists. I can also run the python script directly using just /home/me/project/myscript.py. /usr/bin/python /home/me/project/myscript.py works. So I don't believe this is the cause?
There are a lot of half answers across the internet so I thought I would capture this to save someone else some time.
First, cronjob does a poor job of telling you where this is failing. I recommend sending stderr output to a log file like this:
Crontab Command:
# m h dom mon dow command
* * * * * /path/to/your_file.sh >> out.txt 2>&1
As this is likely running the command as user, check home directory for the log file. Note this script runs every minute which is good for debugging.
The next issue is you probably have a path problem... as script likely is trying to execute from your home directory. This script sets the current directory, echos it to file, and then runs your program.
Try this :
Script File
#!/bin/sh
cd "$(dirname "$0")";
CWD="$(pwd)"
echo $CWD
python your_python_file.py
Hope this saves someone else some debugging time!!!
What happens when you type
/home/me/project/myscript.py into the shell?
Can you explicitly use /usr/bin/python in your crontbb command?
Can you either use an absolute path to your test.db or cd to the correct directory then execute your python script?
This is helpful to have debug statements in your python and log some data. Crontab can be very tricky to debug.
It is possible that the script does not start because it cannot locate the python interpreter. Crontab environment may be very different from the shell environment which you are using. The search paths may be differ significantly.
Also, you test your script by starting the python interpreter explicitly while you expect the crontab to only start the script.
I put this line at the top of my python scripts:
\#!/bin/env python
This line will help locate the interpreter regardless of which directory it is installed in as long as it is in the search path.
It's usually because the python used by crontab is different from the one you use in the shell.
The easiest way to solve this is:
get the python you use in the shell:
$ which python # it may be "python3" or something else
/usr/bin/python
use that specific python in crontab file:
* * * * * /usr/bin/python test.py
Also want to mention that using env -i /bin/bash --noprofile --norc in the shell lets you have the same environment as the one used by crontab, and this is super helpful to debug.
Typically, crontab problems like this are caused by the PATH environment variable being more restrictive/different than what your normal user's PATH environment is. Since your shell uses the PATH environment to find the executable (e.g. /usr/bin/python is found in /usr/bin when you type "python" at a shell prompt), when the PATH is missing common locations, like /usr/bin or /usr/sbin, your cron job will fail. This has bit me many times. The simple fix is just to explicitly set the PATH yourself near the top of your crontab file, before any commands that need it. So, just edit the crontab as usual and add something like this near the top (if your binary is not in one of the below paths, you'll need to add it after a colon):
PATH=/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin
Alternately, just use absolute paths to your binaries and scripts in crontab.
Try this
* * * * * cd <directory_where_python_file_is> && bin/app etc/app_defaults.yaml
There is some path issue with cron. So when you move to directory with python file, cron works like charm!
I'd got the same problem. Despite the fact that the script executed manually was working, in crontab no options mentioned above were working at all. I've moved my script from /home/user/script_directory/ to /opt/scripts/ and it started to work. Possible cause of the problem should be the access (read) permissions to subfolder located in home directory.
Easiest way to handle this is to add your python installation's path to PATH in top of the shell script.
Something like:
#!/usr/bin/env bash
export PATH="{path to your python installation}:$PATH"
python {python_file_name}.py
As #Shargors said you can test it by
env -i /bin/bash --noprofile --norc
If you are using anaconda for python then the path to use will be :
/home/username/anaconda3/bin/python test.py
While the answers here clearly delineate the problem and solution, I wanted to add another answer which helped me.
If your python script is calling a database, then be sure you can connect to the db properly within the cron env (to identify the cron env--> https://askubuntu.com/questions/23009/reasons-why-crontab-does-not-work). I had a file that would run from the shell, but not as a crontab unless I connected to the database as root from within the python script.
Sometimes I am facing same problem. Whatever I try something as advised here, I may not get result.
So I begin to write "trigger" bash script as follow (let's name it trigger.sh):
#!/bin/bash
/full_path/python_script.py
And I am calling trigger.sh from crontab and everything is fine.
EDIT: Of course, don't forget to do following (give execution right):
$chmod +x python_script.py
$chmod +x trigger.sh
I was working on project that includes paramiko lib, when I run the Check_.py from cmdlin it works perfect but when I set the crontab it fails with error no module name paramiko.
So to make it short:
- there were two different python versions installed 3.7 and 2.4, so I used whreris python3 to locate the python path /usr/local/bin/python3.7m so replacing the python with the path will solve the issue.
Example
* * * * * cd /home/MKhair/hlthchk/BR/ && /usr/local/bin/python3.7m /home/MKhair/hlthchk/BR/Check_.py
* * * * * cd [ path-to-the-script-dir] && [path-to-python] [path-to-the-script]
Try to put in your crontab:
* * * * * python /path/to/your/script.py
rather than
* * * * * /path/to/your/script.py
Also the shebang line is #!/usr/bin/env python in some environments. env is an executable, and you have to know where it lives with "$ which env".
Is the cron user (where the script fails) and the terminal user (when the script succeeds) are same ?
Can you redirect the job output to some file as mentioned in Cron Job Log - How to Log?. We could see whether that helps.
This might be helpful for someone. I was having this same issue (or at least a similar issue) and what helped me was to get the path in which Python (Be aware of the version you want to use python, python3, etc...) by running this:
which python3
And then, I replaced python3 for the full path of python3 in my crontab file.