Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crontab won't run python on Mac OS

Tags:

python

macos

cron

I have chased down every answer I can find and tried everything, but I still can't get my crontab to run python. I even created a shell script to run the python, thinking that isolation would help, but it still doesn't work.

I have the following entries in crontab

* * * * * echo "hello" >> /tmp/test2.txt
* * * * * work.sh

the first line just runs every minute so that I can verify cron is running. I have verified that it is running. Every minute I see a new "hello" in test2.txt

the second line runs the following script named work.sh

#! /usr/bin/env zsh
echo "Hello World!" >> /tmp/test2.txt
/opt/miniconda3/bin/python3.7 hellopy.py

hellopy.py then writes "Hello from Python" into test2.txt, like so:

with open('/tmp/test2.txt','a') as test_txt:
        test_txt.write("Hello from Python")

when I run work.sh manually I get what I expect in test2.txt:

Hello World!
Hello from Python

But when I let cron run for a while and look at test.txt, all I see is the entry from from the direct cron line and then the echo command from work.sh. The python line does not write to the file. The text "Hello from Python" does not show up.

hello
Hello World!
hello
Hello World!
hello
Hello World!

I have checked the permissions of the python file -rwxr-xr-x and the text file -rwxrwxrwx and they look fine.

So I know that

  1. The python code works
  2. the shell script can run the python code successfully
  3. crontab is running
  4. crontab can run the shell script
  5. portions of the shell script execute correctly when run by crontab

But for some reason, when crontab runs the shell script, the python command doesn't work. I have also tried the following, none of which work.

  1. running the python script directly from a line in crontab instead of through the shell script.
  2. using 'bash' in the shebang instead of 'zsh'
  3. using a different copy of python in a different path /usr/bin/python3

The solutions that I kept coming across in all my searching have to do with file permissions and absolute paths. I have tried every possible combination of that but nothing seems to help. I am completely stuck. Any help would be appreciated.

like image 384
maderman Avatar asked May 04 '26 16:05

maderman


1 Answers

Capturing the solution from @chepner here for posterity:

The issue was that cron was expecting to find my python file in my home directory, but I had saved the python file in a different one. Once I moved the file to the home directory, everything worked fine.

like image 134
maderman Avatar answered May 06 '26 06:05

maderman