How to avoid console window with .pyw file containing os.system call?

twneale picture twneale · Nov 19, 2009 · Viewed 8.7k times · Source

If I save my code files as .pyw, no console window appears - which is what I want - but if the code includes a call to os.system, I still get a pesky console window. I assume it's caused by the call to os.system. Is there a way to execute other files from within my .pyw script without raising the console window at all?

Answer

Piotr Dobrogost picture Piotr Dobrogost · Oct 19, 2012

You should use subprocess.Popen class passing as startupinfo parameter's value instance of subprocess.STARTUPINFO class with dwFlags attribute holding subprocess.STARTF_USESHOWWINDOW flag and wShowWindow attribute holding subprocess.SW_HIDE flag. This can be inferred from reading lines 866-868 of subprocess.py source code. It might be necessary to also pass subprocess.CREATE_NEW_CONSOLE flag as a value of creationflags parameter as you run under pythonw.exe which does not open a console.

When you use shell=True it just happens that all of the above is set correctly but that doesn't mean it's a proper solution. I would argue it's not because it adds overhead of running command interpreter and parsing arguments. In addition you should keep in mind that (...) the use of shell=True is strongly discouraged in cases where the command string is constructed from external input according to documentation of subprocess module.