3

I have a script that has a GUI, which takes user data and stores it into a text file. It runs another script (an .exe), which waits for user input and then does some work. What I want is for the latter script to hide its console window after reading input from the user, but to continue working in the background.

I tried to run that script with subprocess.call('lastscript.exe', shell=True)or subprocess.Popen('lastscript.exe', shell=True). This doesn't work. I have to take input from the user first, and then hide the console and let the program work in the background.

Eryk Sun
  • 33,190
  • 5
  • 92
  • 111
GLHF
  • 3,835
  • 10
  • 38
  • 83
  • have you considered using a tk window for input? – R21 May 13 '16 at 19:14
  • @R21 I'm using PyQt5 for GUI – GLHF May 13 '16 at 19:26
  • Do you control the source for lastscript.exe? It can easily hide its own console window. – Eryk Sun May 13 '16 at 19:33
  • Yes I have the control, It's just a script that waiting for an input from user (on cmd) then processing codes with that input. After taking the input I want it to hide itself. I tried everything but not succeed.. – GLHF May 13 '16 at 19:38
  • If lastscript.exe is a Python script, then after reading input, you can run the following: `import ctypes;` `kernel32 = ctypes.WinDLL('kernel32');` `user32 = ctypes.WinDLL('user32');` `user32.ShowWindow(kernel32.GetConsoleWindow(), 0)`. – Eryk Sun May 13 '16 at 19:41
  • @eryksun could you post that code as an answer so I can try it better and if it's working I could accept your answer. Also is ctypes 3rd party module? – GLHF May 13 '16 at 19:41
  • ctypes should always be available on Windows in Python's standard library. It's optional on POSIX systems such as Linux, but almost always available. – Eryk Sun May 13 '16 at 19:50
  • BTW, you don't need `shell=True` when running lastscript.exe, and probably shouldn't use it. Only use the cmd.exe shell to run a command that requires built-in shell commands (e.g. `copy` or `dir`) or the Windows `ShellExecuteEx` API. You can run an EXE file directly, without the shell. I removed all references to "cmd" in your question, because the console window is conhost.exe, not cmd.exe. If lastscript.exe is a console application, then it either inherits or creates a new instance of conhost.exe to host its console window. – Eryk Sun May 13 '16 at 19:57

1 Answers1

7

Here's a code snippet to hide the Windows console in a Python script:

import ctypes

kernel32 = ctypes.WinDLL('kernel32')
user32 = ctypes.WinDLL('user32')

SW_HIDE = 0

hWnd = kernel32.GetConsoleWindow()
if hWnd:
    user32.ShowWindow(hWnd, SW_HIDE)
Eryk Sun
  • 33,190
  • 5
  • 92
  • 111
  • 1
    It works on my example script, I'll try it on the main script tho but I think it'll work. Thanks for the answer. – GLHF May 13 '16 at 19:52