Search code examples
pythoncommand-linevbscriptdosstdout

Retrieving the command output of a hidden console?


I run a DOS command from a python environment which retrieves its command output via stdout.

All is working fine excepted that the windows console pops out everytime the script runs, so I need a way to hide the windows console.

Schematically, here is the expected process:

"Console1" runs "hidden Console2" and retrieves its output into "Console1"

I read some recommendations with softwares like "HiddenStart" or "chp" which hide the console when executing DOS commands and batch scripts. Another solution in VBScript can also achieve this result with the following code:

Set oShell = CreateObject ("Wscript.Shell")
Dim strArgs
strArgs = "cmd /c COMMAND GOES HERE"
oShell.Run strArgs, 0, false

But unfortunately, neither "HiddenStart" nor "chp" nor the VBScript script allow to retrieve the command output of the executed commands. "Chp" outputs a stdout but only for the exit process code.

Some might say that one could log the result to a file on disk, and then retrieve the content of the file, but it is not what needed and results in a more complicated process.

So, I'm wondering if it is at all possible to retrieve the command output from a hidden console, is it?

SOLUTION:

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

NOTE OF THE AUTHOR OF THE POST: Hi, this is my first time here, and this question is not a duplicate but a variant. Proof to that is that i made a search before and it was difficult to find the solution before I actually wrote the question. So, moderators need to be a bit more subtle than that. This is a linked, related question or a variant, but not a duplicate, I think. Thanks.


Solution

  • A windows-centric solution could be based on a 'port' from this VBScript:

    mother.py:

    import win32com.client
    oWS = win32com.client.Dispatch("WScript.Shell")
    print("A", "mother starts child")
    oEx = oWS.Exec("cscript ..\\vbs\\child.vbs")
    while not oEx.Stdout.AtEndOfStream:
       print(oEx.Stdout.ReadLine())
    print("B", "mother done")
    

    output:

    A mother starts child
    1 child
    2 child
    3 child
    4 child
    5 child
    B mother done
    

    (ActiveState Python 3.2.2; removing the () from the prints gives a 2.x version (tested with ActiveState Python 2.5.2); to use intrinsics like dir, prepend "%comspec% /c ")