Running a process in pythonw with Popen without a console
From here:
import subprocess
def launchWithoutConsole(command, args):
"""Launches 'command' windowless and waits until finished"""
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
return subprocess.Popen([command] + args, startupinfo=startupinfo).wait()
if __name__ == "__main__":
# test with "pythonw.exe"
launchWithoutConsole("d:\\bin\\gzip.exe", ["-d", "myfile.gz"])
Note that sometimes suppressing the console makes subprocess calls fail with "Error 6: invalid handle". A quick fix is to redirect stdin
, as explained here: Python running as Windows Service: OSError: [WinError 6] The handle is invalid
Hide console with subprocess.Popen
stdout=subprocess.PIPE
has no effect on whether or not a console appears. It just determines whether or not the stdout
of the subprocess is captured in a pipe that you can read from or not.
shell=False
is the default for all subprocess
commands, so you don't need to provide it. It tells subprocess
whether or not to use a shell to execute the provided command. It does not have any effect on whether or not a console appears on any platform.
creationflags = CREATE_NO_WINDOW
will indeed hide the console on Windows (tested on Windows 7, assuming CREATE_NO_WINDOW == 0x08000000
). It will cause an error to use it on non-Windows platforms, though. You should reference this question for a way to only provide creationflags
on Windows, and also for alternative way to hide the console.
Note that the console appearing should only be an issue on Windows. On Posix platforms the console shouldn't ever appear when running subprocesses.
Executing subprocess from Python without opening Windows Command Prompt
How are you calling subprocess.check_call()
? If you pass shell=True
then the window should not be created as this will cause the SW_HIDE
flag to be set for the STARTUPINFO.wShowWindow
attribute.
Example:
subprocess.check_call(["ping", "google.com"], shell=True)
Calling a subprocess without having the system console open
I figured out what I was doing wrong after reading the documentation for subprocess.Popen
The first string in the args
parameter should be the name of the executable. I didn't include the name of the executable as I thought that was taken care of with the executable
paramater.
Disable console output from subprocess.Popen in Python
fh = open("NUL","w")
subprocess.Popen("taskkill /PID " + str(p.pid), stdout = fh, stderr = fh)
fh.close()
How do I hide the console when I use os.system() or subprocess.call()?
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
.
subprocess.Popen in different console
from subprocess import *
c = 'dir' #Windows
handle = Popen(c, stdin=PIPE, stderr=PIPE, stdout=PIPE, shell=True)
print handle.stdout.read()
handle.flush()
If you don't use shell=True
you'll have to supply Popen()
with a list instead of a command string, example:
c = ['ls', '-l'] #Linux
and then open it without shell.
handle = Popen(c, stdin=PIPE, stderr=PIPE, stdout=PIPE)
print handle.stdout.read()
handle.flush()
This is the most manual and flexible way you can call a subprocess from Python.
If you just want the output, go for:
from subproccess import check_output
print check_output('dir')
To open a new console GUI window and execute X:
import os
os.system("start cmd /K dir") #/K remains the window, /C executes and dies (popup)
Constantly print Subprocess output while process is running
You can use iter to process lines as soon as the command outputs them: lines = iter(fd.readline, "")
. Here's a full example showing a typical use case (thanks to @jfs for helping out):
from __future__ import print_function # Only Python 2.x
import subprocess
def execute(cmd):
popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)
for stdout_line in iter(popen.stdout.readline, ""):
yield stdout_line
popen.stdout.close()
return_code = popen.wait()
if return_code:
raise subprocess.CalledProcessError(return_code, cmd)
# Example
for path in execute(["locate", "a"]):
print(path, end="")
Running shell commands without a shell window
I imagine your observation is limited to Windows, since that, I believe, is the only platform on which you'll get that "console flash" issue. If so, then the docs offer the following semi-helpful paragraph:
The startupinfo and creationflags, if
given, will be passed to the
underlying CreateProcess() function.
They can specify things such as
appearance of the main window and
priority for the new process. (Windows
only)
Unfortunately the Python online docs do not reproduce the relevant portion of the Windows API docs, so you have to locate those elsewhere, e.g. starting here on MSDN which leads you here for the creationflags
, and specifically to
CREATE_NO_WINDOW
0x08000000
The process is a console application
that is being run without a console
window. Therefore, the console handle
for the application is not set.
So, adding creationflags=0x08000000
to your Popen
call should help (unfortunately I have no Windows-running machine on which to try this out, so you'll have to try it yourself).
Related Topics
How to Scrape a Website Which Requires Login Using Python and Beautifulsoup
Pipe Subprocess Standard Output to a Variable
Selenium Element Not Visible Exception
Check What Files Are Open in Python
Changing Iteration Variable Inside for Loop in Python
Find Maximum Value of a Column and Return the Corresponding Row Values Using Pandas
Compiling with Cython and Mingw Produces Gcc: Error: Unrecognized Command Line Option '-Mno-Cygwin'
Windows- Pyinstaller Error "Failed to Execute Script " When App Clicked
Does Python Support Multiprocessor/Multicore Programming
Error Installing Geopandas:" a Gdal API Version Must Be Specified " in Anaconda
How to Fix "Importerror: No Module Named ..." Error in Python
Django Aggregation: Summation of Multiplication of Two Fields
How to Pick "X" Number of Unique Numbers from a List in Python
Multiple Inputs and Outputs in Python Subprocess Communicate