拿到控制台所有输出
我这里是自己解析了命令, 暂时没有找到很好的库, 我这里解析的也不全
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| import os import sys from tqdm import tqdm import logging import atexit
class ParseConsoleStr: def __init__(self): self.buffer = [] self.current_line = ""
def parse(self, text): for char in text: if char == "\r": self.current_line = "" elif char == "\b": self.current_line = self.current_line[:-1] else: self.current_line += char if "\n" in text: self.buffer.append(self.current_line.rstrip()) self.current_line = ""
def get_output(self): return "\n".join(self.buffer) + ("\n" + self.current_line if self.current_line else "")
class ConsoleCapture: def __init__(self, output_file="output1.txt"): self.output_file = open(output_file, "w") self.parse = ParseConsoleStr() atexit.register(self.cleanup)
def cleanup(self): self.output_file.write(self.parse.get_output()) self.output_file.close()
sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__
def write(self, text): sys.__stdout__.write(text) self.parse.parse(text)
def flush(self): pass
sys.stdout = ConsoleCapture() sys.stderr = sys.stdout
import time for i in tqdm(range(10)): time.sleep(0.1)
|