'subprocess.CREATE_NEW_CONSOLE is ignored when using "START /B" when shell=True in Popen
I'm running a script in a console window and would like to open a second console and run a sequence of commands.
The command to open that second console must be done using START as it opens a custom console in HCKU\Console.
The issue is that when subprocess.Popen is called using shell=True with START, the process (and therefore the stdout and stderr streams) belong to that shell, and not the subsequently launched program:
import subprocess
p = subprocess.Popen(["start", "/wait", "cmd", "/k", "echo", "hello world"],
shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output, error = p.communicate()
print(output) # b'^C'
print(error) # b''
Even though the terminal will display and "hello world" appears, its not returned to the calling process (the shell) housing START, it instead created a new console when cmd was created. To resolve this, adding the /b flag to START will ensure the program it launches shares the same console:
import subprocess
p = subprocess.Popen(["start", "/wait", "/b", "cmd", "/k", "echo", "hello world"],
shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output, error = p.communicate()
print(output) # b'hello world\r\n\nC:\Users\Me>'
print(error) # b''
However, this does not spawn a new console, recalling I am running the script from an already open console. The result is that even though shell=True is there to create a new console, the current one is shared because of the /b flag in the command. It was my understanding that the /b flag would be applied to the new console opened, but it appears that even though this should take place in theroy, it signals to subprocess.Popen to use the current console instead.
Adding the creationflags=subprocess.CREATE_NEW_CONSOLE does not yield a different result.
With this, how can I...
- Create a new console from the current console using
startand... - Ensure the program launched by
startusing the new console with/b
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
