Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running script with cron doesn't work on mac

Tags:

python

macos

cron

I keep trying to run a cron job that executes a python script every minute. Having executed "which python", I set up the cron job as follows:

SHELL=/bin/bash
MAILTO=MyMac

PATH=bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin

*/1 * * * * * /Users/MyMac/anaconda3/bin/python
/Users/MyMac/desktop/cron_test/test.py

Job's description is in one line and there is a new line character at the end of the definition.

I get the following error in /var/mail/MyMac:

/bin/bash: AnacondaProjects: command not found

So I deleted:

SHELL=/bin/bash

and I got:

/bin/sh: MyMac: command not found

Then I tried all possible combinations of /usr/bin/python with or without lib, anaconda etc., with or without specifying PATH, SHELL, MAIL. Unfortunately, without success.

What am I doing wrong?

Edit

So here's the summary of what I did according to the pieces of advice I received:

I tried:

* * * * * env > /tmp/env.output, 

first I got an error:

/bin/bash: /tmp/env.output: Permission denied, 

so I made a cron Job as sudo. The path in the env.output is:

PATH= bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/Users/MyMac/AnacondaProjects

Finally I set my cronjob (as a normal user not as sudo) to:

SHELL=/bin/bash
[email protected]
PATH=bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/Users/MyMac/AnacondaProjects:/Users/MyMac/anaconda3/bin/python:/usr/bin/env

 * * * * * /Users/MyMac/anaconda3/bin/python /Users/MyMac/desktop/cron_test/test.py

It still doesn't work. The python code is:

#!/usr/bin/env python
def main():
    f = open("test.txt", "w+")
    f.write("HELLO" + '\n')
    f.close()


if __name__ == "__main__":
    print("Print")
    main()

I'm looking forward forward to get and try out new approaches.

like image 332
mångata Avatar asked Dec 17 '22 18:12

mångata


1 Answers

Try doing this:

  1. Open preferences and go to “Security & Privacy” -> “Privacy”
  2. Scroll down to “Full Disk Access” on the left side and select it.
  3. Hit the unlock icon and enter your password
  4. Hit the “+” sign to add an application
  5. Type “command+shift+G” to bring up the got to file dialog box (don’t seem able to navigate the /usr directory)
  6. Enter the full path name to the application (/usr/sbin/cron) and click on “Go”
  7. Click “Open” It should show up in the list with a check mark next to it. I tried it with a simple csh script in cron and it worked. (Credit to my source: https://blog.bejarano.io/fixing-cron-jobs-in-mojave)
like image 183
Barry Avatar answered Jan 04 '23 22:01

Barry