Disable console output from subprocess.Popen in Python
10,980
Solution 1
fh = open("NUL","w")
subprocess.Popen("taskkill /PID " + str(p.pid), stdout = fh, stderr = fh)
fh.close()
Solution 2
import os
from subprocess import check_call, STDOUT
DEVNULL = open(os.devnull, 'wb')
try:
check_call(("taskkill", "/PID", str(p.pid)), stdout=DEVNULL, stderr=STDOUT)
finally:
DEVNULL.close()
I always pass in tuples to subprocess as it saves me worrying about escaping. check_call ensures (a) the subprocess has finished before the pipe closes, and (b) a failure in the called process is not ignored. Finally, os.devnull
is the standard, cross-platform way of saying NUL
in Python 2.4+.
Note that in Py3K, subprocess provides DEVNULL for you, so you can just write:
from subprocess import check_call, DEVNULL, STDOUT
check_call(("taskkill", "/PID", str(p.pid)), stdout=DEVNULL, stderr=STDOUT)
Related videos on Youtube
Author by
Denis Masyukov
Updated on April 17, 2022Comments
-
Denis Masyukov about 2 years
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?
-
MarkI tried that first, for some reason it doesn't parse correctly. >>> ERROR: Invalid Argument/Option - '>'. Type "TASKKILL /?" for usage. That works on the cmd line though.
-
-
Alice Purcell almost 15 yearsI think there's a race condition there — you may close the pipe before your subprocess has finished and cause it to terminate early.
-
orip over 14 years@chrispy - you're correct, I think there should be a .communicate() in there
-
Harvey over 13 years@chrispy,@orip: actually, isn't the answer to add
.wait()
to the subprocess line? -
nbarraille almost 13 yearsJust a silly question: I want to do the exact same thing, and I don't understand why stdout=None prevent the thread to display stuff...
-
Melroy van den Berg over 10 yearsYou can better use: os.devnull instead of "NUL", because that is cross-platform. Windows uses: 'nul' and Linux uses: '/dev/null'.