Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Process and Don't Wait

I'd like to run a process and not wait for it to return. I've tried spawn with P_NOWAIT and subprocess like this:

app = "C:\Windows\Notepad.exe" file = "C:\Path\To\File.txt"  pid = subprocess.Popen(     [app, file],      shell=True,      stdin=subprocess.PIPE,      stdout=subprocess.PIPE, ).pid 

However, the console window remains until I close Notepad. Is it possible to launch the process and not wait for it to complete?

like image 717
Bullines Avatar asked Aug 18 '10 19:08

Bullines


People also ask

Does subprocess run wait for finish?

subprocess. run() is synchronous which means that the system will wait till it finishes before moving on to the next command.

How do I run a Python subprocess in the background?

To start a background process in Python, we call subprocess. Popen . to call subprocess. Popen with a list with the command and command arguments to run the command in the background.

What is process wait Python?

wait() method in Python is used by a process to wait for completion of a child process. This method returns a tuple containing its PID and exit status indication.


2 Answers

This call doesn't wait for the child process to terminate (on Linux). Don't ask me what close_fds does; I wrote the code some years ago. (BTW: The documentation of subprocess.Popen is confusing, IMHO.)

proc = Popen([cmd_str], shell=True,              stdin=None, stdout=None, stderr=None, close_fds=True) 

Edit:

I looked at the the documentation of subprocess, and I believe the important aspect for you is stdin=None, stdout=None, stderr=None,. Otherwise Popen captures the program's output, and you are expected to look at it. close_fds makes the parent process' file handles inaccessible for the child.

like image 100
Eike Avatar answered Sep 19 '22 11:09

Eike


I finally got this to work. I'm running "Python 2.6.6 (r266:84297, Aug 24 2010, 18:13:38) [MSC v.1500 64 bit (AMD64)] win32". Here's how I had to code it:

from subprocess import Popen DETACHED_PROCESS = 0x00000008 cmd = [     sys.executable,     'c:\somepath\someprogram.exe',     parm1,     parm2,     parm3, ] p = Popen(     cmd, shell=False, stdin=None, stdout=None, stderr=None,     close_fds=True, creationflags=DETACHED_PROCESS, ) 

This turns off all piping of standard input/output and does NOT execute the called program in the shell. Setting 'creationflags' to DETACHED_PROCESS seemed to do the trick for me. I forget where I found out about it, but an example is used here.

like image 29
Jon Winn Avatar answered Sep 19 '22 11:09

Jon Winn