2

I need to launch a python console and control its output. I am using python subprocess.Popen() to a create a new instance.

I saved following code in a python script and running it from windows command prompt. When I run the script it launches the python instance in current windows command prompt, do not launch it in a separate console.

p = subprocess.Popen(["C:\Python31\python.exe"], shell=False,
          #       stdin=subprocess.PIPE,
                 stdout=subprocess.PIPE)
out, _ = p.communicate()
print(out.decode())
1
  • Just FYI something to watch out for down the road is that stdout is buffered. So if you're not getting your output when expected you can try manually flushing or using stderr. Commented Aug 2, 2014 at 19:17

2 Answers 2

2

In Windows you can spawn subprocesses in new console sessions by using the CREATE_NEW_CONSOLE creation flag:

from subprocess import Popen, CREATE_NEW_CONSOLE, PIPE

p = Popen(["C:\Python31\python.exe"], creationflags=CREATE_NEW_CONSOLE)
Sign up to request clarification or add additional context in comments.

3 Comments

newly opened console open and get vanish
As I need to control the output I have to use stdout=subprocess.PIPE
I also observe that if I use argument with the command then again newly opened console open and get vanish p = Popen(["C:\Python31\python.exe C:\demo.py"], creationflags=CREATE_NEW_CONSOLE)
1

If you are on windows you can use win32console module to open a second console for your thread or subprocess output. This is the most simple and easiest way that works if you are on windows.

Here is a sample code:

import win32console
import multiprocessing

def subprocess(queue):
    win32console.FreeConsole() #Frees subprocess from using main console
    win32console.AllocConsole() #Creates new console and all input and output of subprocess goes to this new console
    while True:
        print(queue.get())
        #prints any output produced by main script passed to subprocess using queue

if __name__ == "__main__": 
    queue = multiprocessing.Queue()
    multiprocessing.Process(target=subprocess, args=[queue]).start()
    while True:
        print("Hello World in main console")
        queue.put("Hello work in sub process console")
        #sends above string to subprocess and it prints it into its console

        #and whatever else you want to do in ur main process

You can also do this with threading. You have to use queue module if you want the queue functionality as threading module doesn't have queue

Here is the win32console module documentation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.