user2764578
user2764578

Reputation: 61

launch a python console and control its output

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())

Upvotes: 2

Views: 627

Answers (2)

Goldfish Doc
Goldfish Doc

Reputation: 76

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

Upvotes: 1

Edmond Burnett
Edmond Burnett

Reputation: 5186

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)

Upvotes: 2

Related Questions