3

I want to run a shell script that runs a python program and shutdowns after the program is done. Here is what I wrote

#!/bin/bash
python program
sudo shutdown -h now

This just shutdowns the system without waiting for the program to complete. Is there a different command to use that waits for the program to complete?

jordanm
  • 33,009
  • 7
  • 61
  • 76
viper
  • 2,220
  • 5
  • 27
  • 33

3 Answers3

5

What you have in your example should actually only shutdown once the python command has completed, unless the python program forks or backgrounds early.

Another way to run it would be to make the shutdown conditional upon the success of the first command

python command && sudo shutdown -h now

Of course this still will not help you if the python program does anything like forking or daemonizing. Simply try running the python script alone and take note if control returns immediately to the console or not.

jdi
  • 90,542
  • 19
  • 167
  • 203
  • The python script I wrote is a scraper, it is used to get a few html pages from the net. I know for sure that the program is working. – viper Aug 29 '12 at 05:41
  • 2
    I am not suggesting the program is not working. What I am saying it that if it daemonizes or forks, then it will continue to run, but the calling process will return early and allow the shutdown to happen. It really depends solely on what your python program does. When you run it by itself, does it block the shell until it completes? – jdi Aug 29 '12 at 05:45
  • While explaining that he can shutdown only if the python script returns zero is good, he probably wants to run shutdown with sudo, not the python command. – jordanm Aug 29 '12 at 05:54
  • I have written my code in OO structure. So the scraping is done with a method call. @jdi how do I check if it forks (I am not explicitly forking a thread) – viper Aug 29 '12 at 15:33
  • What was the result of running your python script from the shell? Does it sit there and wait or does it immediately give you back a command prompt? – jdi Aug 29 '12 at 16:07
0

You could run the command halt to stop your system:

   #!/bin/sh
   python program
   sudo halt

The python program is running first, and halt would run after its completion (you might test the exit code of your python program). If it does not behave like expected, try to understand why. You could add a logger command before the halt to write something in the system logs.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
0

Alternatively, you can use command substitution like this:

$(command to run your program)

The script waits until the wrapped command finishes before moving onto the next one!

#!/bin/sh
$(python program.py)
sudo shutdown -P 0