views:

782

answers:

2

I run Python 2.5 on Windows, and somewhere in the code I have

subprocess.Popen("taskkill /PID " + str(p.pid))

to kill IE window by pid. The problem is that without setting up piping in Popen I still get output to console - SUCCESS: The process with PID 2068 has been terminated. I debugged it to CreateProcess in subprocess.py, but can't go from there.

Anyone knows how to disable this?

+3  A: 
fh = open("NUL","w")
subprocess.Popen("taskkill /PID " + str(p.pid), stdout = fh, stderr = fh)
fh.close()
Mark
Thank you! This piece actually works. I completely forgot about NUL.
Denis M
I think there's a race condition there — you may close the pipe before your subprocess has finished and cause it to terminate early.
chrispy
@chrispy - you're correct, I think there should be a .communicate() in there
orip
+1  A: 

Does this work?

from subprocess import Popen, PIPE
Popen(("taskkill", "/PID", str(p.pid)), stdout=PIPE, stderr=PIPE).communicate()

I always pass in arrays to subprocess as it saves me worrying about escaping. The Pipe/communicate method is cross-platform — useful for future code, not this particular example, of course.

chrispy