How to run my Python script with Anaconda environment in crontab?

I want to schedule a task with crontab to run a python file in a specific anaconda environment every day at a certain time. I have a python script to do so.

The python script runs if I just execute it with python h.py in the anaconda environment in terminal. h.py is in the home directory.

I am using Ubuntu 20.04, and I haven't refreshed or installed any new cron or crontab

I have tried the following commands to get it work but they just do nothing (the result should be a folder and it is clearly not has been created)

crontab -e

Inside the crontab:

#[long descriptional text]
...
53 13 * * * cd /home/ && /home/user/anaconda3/envs/rapids/bin/python h.py    

This also does nothing: no error message

I have also tried the following:

32 14 * * * cd /home/Documents && /home/user/anaconda3/envs/rapids/bin/python h.py

and

34 14 * * * cd /home/Documents && /home/anaconda3/envs/rapids/bin/python h.py 2>&1

From this answer on Stack Overflow.

This answer on Unix & Linux did not work with normal anaconda.

I have also read the following solutions but nothing has worked.

  • How can I run a Python script using Anaconda from the command line
  • Crontab service file not found despite installed and configured crontab
  • Crontab doesnt run python script
  • Execute Python script via crontab
  • Crontab Python script does not run with Anaconda on Linux server

One thing I've thought of but not tried is installing a daemon for crontab as is recommended in this answer, but I could not find cronie to install for Ubuntu.


!! Give .sh file permission to run chmod u+x my_shell_file_name.sh

If the Python file only need python (not other library) 56 16 * * * /home/MY_ACTUAL_USERNAME/anaconda3/envs/rapids/bin/python /home/MY_ACTUAL_USERNAME/Documents/h.py

If Python file requires other python libraries that are in the anaconda environment:

  • create a SHELL script

    nano my_shell_file_name.sh
    
  • Example of what should be inside the file

    #!/bin/bash
    #conda activate rapids WRONG
    source ~/anaconda3/bin/activate MY_ANACONDA_ENVIRONMENT_NAME #correct
    #python Documents/my_python_file_name.py WRONG SEPARATLY GO TO FOLER WHTAN EXECUTE EITH python
    cd ~/Documents/folder_where_python_file_is/ #correct
    python my_python_file_name.py #correct
    conda deactivate
    
  • start up crontab with

    crontab -e
    
  • example of what you can add to the end of this crontab file

    43 21 * * * /home/MY_ACTUAL_USERNAME/my_sehell_file_name.sh