11

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?

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Denis Masyukov
  • 2,966
  • 4
  • 25
  • 20
  • What is the problem with subprocess.Popen("taskkill /PID " + str(p.pid) + " > NUL")? – Svetlozar Angelov Aug 07 '09 at 13:50
  • Maybe because python runs on Windows? It says that '>' is not a valid option of taskkill command – Denis Masyukov Aug 07 '09 at 14:12
  • 1
    I 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. – Mark Aug 07 '09 at 14:14

2 Answers2

18
from subprocess import check_call, DEVNULL, STDOUT

check_call(
    ("taskkill", "/PID", str(p.pid)),
    stdout=DEVNULL,
    stderr=STDOUT,
)

I always pass in tuples (or lists) 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.

If you're stuck in python 2, subprocess doesn't provide DEVNULL. However, you can replicate it by opening os.devnull (the standard, cross-platform way of saying NUL in Python 2.4+):

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()
Alice Purcell
  • 12,622
  • 6
  • 51
  • 57
11
fh = open("NUL","w")
subprocess.Popen("taskkill /PID " + str(p.pid), stdout = fh, stderr = fh)
fh.close()
Mark
  • 106,305
  • 20
  • 172
  • 230