Search code examples
pythonpython-3.xcmdcommand-prompt

How to save current cmd-output


Is there a way to get whats currently displayed on the windows command prompt?

For example:

print('some text')
print('some different text')

>>> some text
>>> some different text

a = save_whats_on_cmd()
>>> a = 'some text \n some different text'

Solution

  • @Rick_2650 here is an improved version of the function as you wanted

    # log function prints message and
    # saves the output in log.txt of
    # the current working directory
    # sample usage [green text ANSI 1;32]:-
    #     >>> log("hello", "world", colour="1;32")
    #
    # @param   objects  *args    objects we want to print
    # @param   string   colour   ANSI style colour codes 
    # @param   string   sep      Separator for __str__ of objects    
    # @param   string   end      String to be added at lineend
    # @param   string   logfile  name of logfile
    # @return  void
    def log(*args, sep=" ", colour="0", end="\n", logfile="log.txt"):
    
        printable_array = []
        colour = "\033[" + colour + "m"
    
        with open(logfile, "a") as file:
            for each in args:
                printable_array.append(colour+each+"\033[0m")
                file.write(each+sep) # seperator will effect the final entry
            file.write(end)
    
        print(*printable_array, sep=sep, end=end, flush=True)