2

I have a script where normally I would not want the console window displayed like a .py file does and using the .pyw extension does that just as it's designed to do.

My question, is there a way to bring the running script's console window up from a .pyw file?

tgikal
  • 1,667
  • 1
  • 13
  • 27
  • 1
    The interpreter is the language runtime that evaluates source code and, for CPython, provides a C API for extensions. I think you want a shell of some sort, probably the default REPL, which is sometimes called the "interactive interpreter" (e.g. see the standard-library's "code" module), though it's an inaccurate name. This is possible in a pythonw.exe GUI process. Allocate a console via `kernel32 = ctypes.WinDLL('kernel32', use_last_error=True);` `kernel32.AllocConsole()`. Set up `sys.[stdin|stdout|stderr]` by opening "CONIN$" and "CONOUT$". Then call the code module's `interact` function. – Eryk Sun Jan 11 '19 at 03:08
  • Yeah, I didn't really know what to call it, calling it shell just gets a ton of "how to open command prompt" responses. I was more interested in having it bring up the shell that it would have been printing to during operation. – tgikal Jan 11 '19 at 13:51
  • Looks like https://stackoverflow.com/questions/6673022/windows-gui-console-output-linux-style and https://stackoverflow.com/questions/7883214/how-to-print-to-stdout-from-python-script-with-pyw-extension are related. It may be better to just run as a .py and hide the console it sounds like. – tgikal Jan 11 '19 at 14:31
  • Getting a new console via `AllocConsole` is pretty simple, I think. Definitely do not use `AttachConsole` to grab someone else's console. For standard I/O, that's used at most to write some lines, but even that can be confusing to the user. Attaching to run a shell would be a mess. The proper use for `AttachConsole` is to get the console window handle, or scrape the console screen buffer, or some other use of the console API such as generating a control event. – Eryk Sun Jan 12 '19 at 00:03

1 Answers1

0

Ended up going with the method of using a .py file and suppressing the console window.

Bound a simple toggle function to a button:

import ctypes

def raise_console(console_toggle):
    """Brings up the Console Window."""
    if console_toggle:
        # Show console
        ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 4)
    else:
        # Hide console
        ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0)
    console_toggle = not console_toggle

console_toggle = False
tgikal
  • 1,667
  • 1
  • 13
  • 27