如何保存当前的命令输出

How to save current cmd-output

有没有办法获取 windows 命令提示符当前显示的内容?

例如:

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

>>> some text
>>> some different text

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

创建一个文件,假设mylib.py

import sys


class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout
        self.log = open('log.dat', 'w')

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

    def flush(self):
        pass

然后打开你的解释器:

>>> from mylib import Logger
>>> import sys
>>> sys.stdout = Logger()
>>> print(1)
1
>>> print(2)
2
>>> print(3)
3
>>> exit()

参见log.dat:

1
2
3

我建议用你自己的函数包装打印件

>>> output_file_name = "output.txt"

>>> def cmd_print(*args, **kwargs):
...     with open(output_file_name, "a") as file:
...         for each in args:
...             print(each.__str__())
...             file.write(each.__str__()+"\r\n")
...             # \r\n linebreaks are dos only use \n for *nix
...
>>> cmd_print("you can do strings", ["lists", "too"])

答案假定您可以控制代码 这意味着您可以选择替换打印命令

如果不是这种情况,快速而肮脏的方法是覆盖打印

>>> output_file_name = "output.txt"
>>> pythonic_print = print
>>> def print(*args, **kwargs):
...     with open(output_file_name, "a") as file:
...         for each in args:
...             pythonic_print(each.__str__())
...             file.write(each.__str__()+"\r\n")
...             # \r\n linebreaks are dos only use \n for *nix
...
>>> print("you can do strings", ["lists", "too"])

我使用了@omar 的解决方案来解决我的问题,并对其进行了修改以使其完全适合我的需要。这是我写的:

def log(text, **kwargs): # possible arguments: colour, end
    logfile = open('log.txt', 'a')
    if kwargs == {}: 
        # normal print statement: no colour, no end=''
        print(text)
        logfile.write(text + '\n')
    else:
        if 'colour' in kwargs and 'end' in kwargs: 
            # both colour and end=''
            print(f'\x1b[{kwargs["colour"]}m{text}\x1b[0m', end='', flush=True)
            logfile.write(text)
        elif 'colour' in kwargs:
            # only colour
            print(f'\x1b[{kwargs["colour"]}m{text}\x1b[0m')
            logfile.write(text + '\n')
        elif 'end' in kwargs: 
            # only end=''
            print(text, end='', flush=True)
            logfile.write(text)
    logfile.close()

我不希望 \x1b[1;31;42mSOMETEXT\x1b[0m 之类的东西出现在日志中,所以我将 colour-stuff 作为参数。 log-file 中的结果只有 SOMETEXT.

对于 end 参数,分配给它的内容无关紧要。我只是需要被提及。

这使得 log-file 就像第二个命令提示符一样 - 只有无色。

如果有人有任何关于如何改进我的功能的想法,请告诉我,因为我觉得它看起来很乱。 :P

感谢回复:)

@Rick_2650这里是你想要的功能的改进版本[​​=11=]

# 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 = "3[" + colour + "m"

    with open(logfile, "a") as file:
        for each in args:
            printable_array.append(colour+each+"3[0m")
            file.write(each+sep) # seperator will effect the final entry
        file.write(end)

    print(*printable_array, sep=sep, end=end, flush=True)