Search code examples
pythonconsolewindow

Python: Create another python console window sharing same data


I'm trying to make a debug console window appear (Needs to share data with the script), still having the main console open. The only way I know how to do it is to execute a second script, and share data with a file..

I would like for the second window to be an actual console.

I'm on Windows 7, and my script doesn't need to be very compatible.


Solution

  • If you are on windows you can use win32console module to open a second console for your child thread(since you want them to share same data) output. This is the most simple and easiest way that works if you are on windows.

    Here is a sample code:

    import win32console
    import threading
    from time import sleep
    
    def child_thread():
        win32console.FreeConsole() #Frees child_thread from using main console
        win32console.AllocConsole() #Creates new console and all input and output of the child_thread goes to this new console
       
        while True:
            print("This is in child_thread console and the count is:",count)
            #prints in new console dedicated to this thread
    
    if __name__ == "__main__": 
        count = 0
        threading.Thread(target=child_thread, args=[]).start()
        while True:
            count+=1
            print("Hello from the main console - this is count:", count)
            #prints in main console
            sleep(1)
            #and whatever else you want to do in ur main process
    

    There is also a better method of using queues from the queue module as it gives you a more control over race conditions.

    Here is the win32console module documentation