【问题标题】:How to get last python output?如何获得最后的python输出?
【发布时间】:2022-06-11 12:36:46
【问题描述】:

我正在尝试使用 os.popen、subprocess.run、subprocess.Popen 函数获取最后一个 python 输出,正如这个古老的问题 How can I get terminal output in python? 中所示 它似乎不起作用。

基本上我想做的是检测最后一个输出,例如:

print("Hello World")
last_output = get_last_output()
print() # For avoiding confutions

print(last_output)
# Would print "\n"


print("Hello World", end="")
last_output = get_last_output()
print() # For avoiding confutions

print(last_output)
# Would print "Hello World"

我也希望这个遮阳篷可以独立于控制台工作

【问题讨论】:

  • 你想要subprocess.check_output吗?它基本上是Popen,但它会同步并阻止你的代码,直到它完成。
  • 它“有效”或“无效”似乎有效?如果它“不起作用”,究竟是什么不起作用?
  • @EricJin 在这种情况下你会如何使用它?我不明白它的文档docs.python.org/3/library/…
  • @YevhenKuzmovych 他们不打印文件中的最新输出,他们只是打印当前文件路径的字节数
  • 我现在明白了,所以您想将最后一个运行的函数的输出捕获到标准输出?你需要阅读sys.stdout

标签: python printing console output


【解决方案1】:

假设“最后一个输出” 是最后一个写入sys.stdout 的非空字符串,一种选择是使用write(data) 和@987654324 分配一个对象@方法到sys.stdout,所以你可以保存应该是输出:

import sys


class StdoutHandler:
    def __init__(self):
        self.last_output = ""
    
    def start(self):
        self._handled_stdout = sys.stdout
        sys.stdout = self
    
    def write(self, data: str):
        # write(data="") is called for the end kwarg in print(..., end="")
        if data:
            self.last_output = data
            self._handled_stdout.write(data)

    def end(self):
        sys.stdout = self._handled_stdout
    
    def flush(self):
        self._handled_stdout.flush()



stdout_handler = StdoutHandler()
stdout_handler.start()


print("Hello World")
last_output = stdout_handler.last_output
print(repr(last_output))
# Prints '\n'


print("Hello World", end="")
last_output = stdout_handler.last_output
print()
print(repr(last_output))
# Prints 'Hello World'

print("Hello", "World", end="")
last_output = stdout_handler.last_output
print()
print(repr(last_output))
# Prints 'World'

我的想法来自How to duplicate sys.stdout to a log file?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-26
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 2021-12-15
    • 2019-03-09
    相关资源
    最近更新 更多