Sumit Paliwal Sumit Paliwal - 2 months ago 7
Python Question

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.

Answer

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.

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.