3

I am trying to use os.system (soon to be replaced with subprocess) to call a shell script (which runs a process as a daemon)

os.system('/path/to/shell_script.sh')

The shell script looks like:

nohup /path/to/program &

If I execute this shell script in my local environment, I have to hit enter before being returned to the console as the shell script is running a process as a daemon. If I do the above command in python, I also have to hit enter before being returned to the console.

However, if I do this in a python program, it just hangs forever.

How can I get the python program to resume execution after calling a shell script that runs a process as a daemon?

Matthew Moisen
  • 16,701
  • 27
  • 128
  • 231

2 Answers2

3

From here -

Within a script, running a command in the background with an ampersand (&) may cause the script to hang until ENTER is hit. This seems to occur with commands that write to stdout.

You should try redirecting your output to some file (or null if you do not need it), maybe /dev/null , if you really do not need the output.

 nohup /path/to/program > /dev/null &
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
  • Hi Anand, nohup by default writes to nohup.out (unless you redirect it). However I tried the following: `nohup /path/to/program > nohup.out &` and also `nohup /path/to/program & > nohup.out` but both required that I hit `enter` in both the bash and in python. – Matthew Moisen Jul 29 '15 at 20:27
  • However, when run in my python program, it doesn't hang any more, thanks! Any idea on the discrepancy? – Matthew Moisen Jul 29 '15 at 20:28
  • Sorry , maybe you should have tried to redirect both stout and stderr – Anand S Kumar Jul 30 '15 at 00:36
0

Why don't you trying using a separate thread? Wrap up your process into something like

def run(my_arg):
    my_process(my_arg)

thread = Thread(target = run, args = (my_arg, ))
thread.start()

Checkout join and lock for more control over the thread execution. https://docs.python.org/2/library/threading.html

zom-pro
  • 1,571
  • 2
  • 16
  • 32