1

I wrote a Python script which backs up mongoDB, and it works fine when I test run directly in terminal.

However, I get an error from cron saying mongodump: command not found - although the command mongodump works fine when I run the script directly in terminal.

Contents of crontab -e:

* * * * * cd <path-to-script> && python3 script.py
S3DEV
  • 8,768
  • 3
  • 31
  • 42
Cerceis
  • 770
  • 3
  • 14
  • 4
    [This question/answer](https://stackoverflow.com/a/62864649/6340496) might be helpful. – S3DEV Jul 15 '20 at 09:41

2 Answers2

2

After looking into the post provided by S3DEV's.

Running the full env path of mongodump into the python script worked. To get the full path of mongodump, in terminal:

which mongodump
>>/usr/local/bin/mongodump

In my case i am using os.system() in my script.

os.system(/usr/local/bin/mongodump [commands])

instead of

os.system(mongodump [commands])
Cerceis
  • 770
  • 3
  • 14
2

This is because programs started from cron don't get the environment your login shell uses. In particular, PATH is usually quite minimal. The tried and tested way to run scripts from cron is:

  • Always use an absolute path to a script in the crontab, say /path/to/script.
  • The beginning of /path/to/script sets and exports PATH and any other variables needed, e.g. with export PATH=$(/usr/bin/getconf PATH):/usr/local/bin

You can test whether any script would run with a reduced environment with

env -i HOME=$HOME /path/to/script

If that runs ok, it is ready for cron.

Jens
  • 69,818
  • 15
  • 125
  • 179