Asked  7 Months ago    Answers:  5   Viewed   262 times

I wrote some statements like below:

os.system(cmd) #do something
subprocess.call('taskkill /F /IM exename.exe')

both will pop up a console.

How can I stop it from popping up the console?

 Answers

72

The process STARTUPINFO can hide the console window:

si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
#si.wShowWindow = subprocess.SW_HIDE # default
subprocess.call('taskkill /F /IM exename.exe', startupinfo=si)

Or set the creation flags to disable creating the window:

CREATE_NO_WINDOW = 0x08000000
subprocess.call('taskkill /F /IM exename.exe', creationflags=CREATE_NO_WINDOW)

The above is still a console process with valid handles for console I/O (verified by calling GetFileType on the handles returned by GetStdHandle). It just has no window and doesn't inherit the parent's console, if any.

You can go a step farther by forcing the child to have no console at all:

DETACHED_PROCESS = 0x00000008
subprocess.call('taskkill /F /IM exename.exe', creationflags=DETACHED_PROCESS)

In this case the child's standard handles (i.e. GetStdHandle) are 0, but you can set them to an open disk file or pipe such as subprocess.DEVNULL (3.3) or subprocess.PIPE.

Tuesday, June 1, 2021
 
PandemoniumSyndicate
answered 7 Months ago
55

By using psutil:

import psutil, os

def kill_proc_tree(pid, including_parent=True):    
    parent = psutil.Process(pid)
    children = parent.children(recursive=True)
    for child in children:
        child.kill()
    gone, still_alive = psutil.wait_procs(children, timeout=5)
    if including_parent:
        parent.kill()
        parent.wait(5)

me = os.getpid()
kill_proc_tree(me)
Wednesday, June 2, 2021
 
BetaRide
answered 7 Months ago
17

Ok here is how I got it to work.

env = os.environ
proc = subprocess.Popen(args, env=env)
Thursday, August 12, 2021
 
Noob_Programmer
answered 4 Months ago
22

Use pythonw.exe instead of python.exe

Monday, August 30, 2021
 
BradM
answered 3 Months ago
38
        Process p = new Process();
        StreamReader sr;
        StreamReader se;
        StreamWriter sw;

        ProcessStartInfo psi = new ProcessStartInfo(@"bar.exe");
        psi.UseShellExecute = false;
        psi.RedirectStandardOutput = true;
        psi.RedirectStandardError = true;
        psi.RedirectStandardInput = true;
        psi.CreateNoWindow = true;
        p.StartInfo = psi;
        p.Start();

This will start a child process without displaying the console window, and will allow the capturing of the StandardOutput, etc.

Tuesday, September 28, 2021
 
Drew Noakes
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share