7

I want to repeatedly call a script via cron in a docker container, but when I switch from one time execution to execution via cron the official python image suddenly can't seem to find python.

Dockerfile:

FROM python:3.7-slim

COPY main.py /home/main.py

#A: works
CMD [ "python", "/home/main.py" ]

#B: doesn't work
#RUN  apt-get update && apt-get -y install -qq --force-yes cron
#COPY hello-cron /etc/cron.d/hello-cron
#CMD ["cron", "-f"]

main.py

import time

for i in range(90000):
    print(i)
    time.sleep(5000)

hello-cron:

* * * * * root python /home/main.py > /proc/1/fd/1 2> /proc/1/fd/2
#

When I switch A for B in the Dockerfile the error message is: /bin/sh: 1: python: not found

Thank you all for he quick responses! Adding PATH=/usr/local/bin in the cron file solved my problem.

peer
  • 4,171
  • 8
  • 42
  • 73
  • 1
    Does this answer your question? [How to get CRON to call in the correct PATHs](https://stackoverflow.com/questions/2388087/how-to-get-cron-to-call-in-the-correct-paths) – omajid Apr 30 '20 at 00:08
  • 1
    `which python` to know the absolute path of python on the system. – Pedro Lobito Apr 30 '20 at 00:09

1 Answers1

8

Cron doesn't set up the PATH environment variable the same as a normal login shell so python can't be found. It should work if you specify a complete path to the Python executable, e.g. replace python with /usr/bin/python (or whatever the path to your Python executable happens to be). Alternatively you can explicitly set the PATH environment variable in the Cron configuration file to include the directory where Python can be found.

Weeble
  • 17,058
  • 3
  • 60
  • 75
  • 1
    Interestingly the complete path `PATH=/usr/local/bin/python` did not work for me, only the path to the directory `PATH=/usr/local/bin` did. – peer Apr 30 '20 at 08:33
  • Oh, no, I meant using an absolute path to specify the python executable. Of course, changing the PATH environment variable works too, though as you sat you need to specify the directory. I'll reword my answer. – Weeble Apr 30 '20 at 16:14
  • jesus crispy donut! this work for me! thx :) – SecY Jun 21 '23 at 03:56