Sumit Paliwal
Sumit Paliwal

Reputation: 395

Running program/function in background in Python

I'm trying to run a program/function (whichever is possible), from another python program, that will start it and close. Example. python script "parent.py" will be called with some input, that input data will be passed to function/program "child", which will take around 30 minutes to complete. parent.py should be closed after calling "child".

Is there any way to do that?

Right now I'm able to start the child, but parent will be closed only after completion of child. which, I want to avoid.

Upvotes: 2

Views: 1007

Answers (2)

Syed Ehtsham Abbas
Syed Ehtsham Abbas

Reputation: 502

To run any program as background process. This is the easiest solution and works like a charm!

import thread

def yourFunction(param):
    print "yourFunction was called"

    thread.start_new_thread(yourFunction, (param))

Upvotes: 1

John1024
John1024

Reputation: 113814

As I understand it, your goal is to start a background process in subprocess but not have the main program wait for it to finish. Here is an example program that does that:

$ cat script.py
import subprocess
subprocess.Popen("sleep 3; echo 'Done!';", shell=True)

Here is an example of that program in operation:

$ python script.py
$ 
$ 
$ Done!

As you can see, the shell script continued to run after python exited.

subprocess has many options and you will want to customize the subprocess call to your needs.

In some cases, a child process that lives after its parent exits may leave a zombie process. For instructions on how to avoid that, see here.

The alternative: making subprocess wait

If you want the opposite to happen with python waiting for subprocess to complete, look at this program:

$ cat script.py
import subprocess
p = subprocess.Popen("sleep 3; echo 'Done!';", shell=True)
p.wait()

Here is an example its output:

$ python script.py
Done!
$ 
$ 

As you can see, because we called wait, python waited until subprocess completed before exiting.

Upvotes: 1

Related Questions