2

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.

3
  • 1
    Have you looked at the subprocess module? Commented Oct 15, 2015 at 4:39
  • yes, it has the same issue, It will also wait for the child process to complete and then terminate the main program. Commented Oct 15, 2015 at 4:51
  • There are options to make subprocess wait like that but you don't have to set those options. See my answer for an example. Commented Oct 15, 2015 at 5:11

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.