Search code examples
pythonprintingcmdwindowoutput

Print the output of a python code in a new cmd window


I want to open a cmd window and use it to print some variables. The problem is that, the code below, opens 5 independent windows (ovbiously).

import os

for i in range(0,5):
    command = "start cmd /K echo " + str(i+1)
    os.system(command)

I dont know if I can have a reference or a link to the already opened window to send it the commands.

The desired result would be...

1
2
3
4
5

...on the same window

The purpose is to be able to print on that window certain variables during the execution of a code.

I'm stucked and I don't know if that is even possible. Im on W10 with Python 2.7

Thank you very much


Solution

  • What you want is actually the logging package from the stdlib. Simply configure your logger to write to a file, and in another command window use the Windows equivalent of unix's tail -f <filename> command to check what gets logged in (almost) real time.

    Note that you could also just log (still using the logging lib) to sys.stderr, launch your python app from a command window and then you'll have all the logging in the very same command window (typical unix development flow).

    As a last note: the logging lib is quite extensible so you could even write your own logging.handler that opens it's own windows and displays logs messages in it if you really want (but that would really be a waste of time).