Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

A python script to shutdown system works fine from the terminal but doesn't work when included in crontab. The script is called by cron but ends with an error 'shutdown command not found'or 'init 0 command not found'. I am using fedora 17 and the script is executed from root's crontab.

#!/usr/bin/python
import os
os.system('shutdown')
os.system('init 0')
share|improve this question
    
i rather call it in crontab as 'python shutdown.py' with env set in cron. All other python script work fine except this one and in particular the shutdown command. –  Rajkumar R Jul 18 '12 at 14:41

2 Answers 2

up vote 1 down vote accepted

I guess the first line of your snippet is supposed to be something like:

#!/usr/local/bin/python

or, if you also make sure you set an appropriate value for PATH in your crontab:

#!/bin/env python

What does your crontab entry look like? Don't forget that cron sets a very limited environment, so you will need to provide the full path to the script file so that cron can find it.

Additionally, python probably can't find shutdown when called from cron, because it will inherit cron's limited environment. Try providing the full path to the shutdown command in your os.system() call.

share|improve this answer
    
It is usually preferred to use #!/usr/bin/env python as that will use the python from PATH instead of a specific one. (Assuming that PATH is set correctly, which it may not be in a crontab) –  mrb Jul 18 '12 at 14:47
    
So, for use within a crontab, then, the preferred approach is an explicit path, no? –  D_Bye Jul 18 '12 at 14:49
    
I would argue that the preferred approach is to fix your PATH with another crontab line :) –  mrb Jul 18 '12 at 14:50
    
Yuh, you're probably right! I know all about the portability concerns, etc, but as I only use FreeBSD, where everything is always in the same place, it's not really enough of a concern to make me break my lazy habits! I'll edit my answer. –  D_Bye Jul 18 '12 at 14:57
    
calling os.system('/sbin/shutdown') fixed the issue –  Rajkumar R Jul 18 '12 at 15:30

Your PATH isn't what you're expecting it to be. According to the (Debian version of the) crontab(5) man page, the PATH environment variable is set to /usr/bin:/bin for programs run from cron. You can change this by adding a PATH= line to the top of your crontab, for example:

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

This will change the path for all crontab entries below the PATH= line, up to the next PATH= line. See the crontab(5) man page for more details.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.