Python subprocess with shell = True: redirect and platform-independent subprocess killing

It's hard for me to get what I want from the python subprocess module (which should be a unified / platform-independent abstraction, afaik, but don't make me start with this :)).

So, for me, what I need is the following. I want to

  • Launch an external (stdio) application (possibly with a subprocess) where I use shell-style redirects (e.g.. / Myapp> stdout_log> stderr_log)
    • Basically, I want to execute a shell command line, so I have to specify shell = True for subprocess.Popen () (otherwise redirects on the command line will not work)
  • I want to run this command line in async mode (so that it runs as an independent subprocess, but my python process will not wait for completion)
  • (My parent python process will check child process logs from time to time to extract information, but this is not relevant)
  • If my parent python process decides, it should be able to terminate this child process.

Now my main problems are that

  • Basically I have to use shell = True to get redirects to work
  • Handling the child stdout / stderr in the parent python process is not an option since I could not find the functionality for this in standby mode (and the parent python process must do other things while the child process is running)
  • shell = True, subprocess.kill() ,
  • , (, , Linux Windows).

, . / - , :( (, , )

UPDATE (2010-10-13):

( shell = False), subprocess.Popen.kill() (, - "", .)

preexec_fn, sid , unix-only: -

+5
4

, , , ( ) , , . , python (, , - ), . , .

, subprocess - Windows, . subprocess , , , popen, popen2 .. , .

+4

, python, shell=True, . - "" , . .

script:

childProcess = subprocess.Popen('python other.py', shell=True)

" ", :

subprocess.call("ps -ef | awk '$3 == \"" + str(childProcess.pid) + "\" {print $2}' | xargs kill -9", shell=True)
childProcess.kill()

( ps -ef parentage, .

, Ubuntu, Mac OSX, Mac , , .

+3

:

shell = True,

stdout stderr?

out_log = open("stdout_log", "w")
err_log = open("stderr_log", "w")
subproc = subprocess.popen(..., stdout=out_log, stderr=err_log, ...)

stdout/stderr python , ( python , )

- Windows. Unix- select. Windows select , .

shell = True, subprocess.kill() ,

, shell=True , .

, (, , Linux Windows)

Windows? , , Task Task End Task 100% . Linux , , , .

, Windows -. , shell=False, , , , .

+2

All Articles