Running a Python Script using Cron?
Asked Answered
C

1

6

I have a python script that I'd like to add to cron.

The script has +x permission on it.

How shall I add it to crontab? (say, I want it to run every minute).

Important: when I navigate (using the shell) to the script's folder, I cannot run it using "./script_name.py"; it doesn't work. Yet, when I run it using "Python script_name.py", everything works.

Crazyweed answered 20/12, 2010 at 2:37 Comment(0)
R
8

From cron you should be running the script as script_name.py and your script meets the following criteria:

  • Executable bit is set
  • The script's hash-bang is set correctly eg. #!/usr/bin/env python
  • it is accessible from the PATH
    • e.g. place it in /usr/local/bin/ or /opt/local/bin/ (and they are accessible to your system PATH.)

If these conditions are met, you should be able to run it from anywhere on your local system as script_name.py

Reproduction answered 20/12, 2010 at 2:41 Comment(6)
Thank you. What if the script resides in a different area (not in '/usr/local/bin/' or '/opt/local/bin/')? is there anything I can do to have it run?Crazyweed
Of course, but you still have to add it's folder location to your PATH, the reason I suggest those locations, is because that's where your optional/user local system bins/scripts should live (historically). But there's no reason you can't use another folder, Also you can call the script using an absolute pathname /myfolder/sub/bin/etc/wherever/script_name.py in your crontab. It's just not the conventional way of doing it, and therefore creates confusion if this system needs to be administered by someone else (or you in the future)Reproduction
Thank you for your help. I tried to do this, and the script seems to work via cron, but for some reason, stops after few seconds. more information here: #4487645 do you happen to know what I am missing?Crazyweed
I had a look at the other question, the comments there are the things I would've suggested myself. In particular try using logging to catch what's happening.Reproduction
I restarted the computer and everything works fine now. Thank you for your help!Crazyweed
Hopefully the problem won't come back :)Reproduction

© 2022 - 2024 — McMap. All rights reserved.