将Python输出重定向到控制台窗口

0 投票
1 回答
2037 浏览
提问于 2025-04-17 23:26

我想要做的是把Python的输出信息(也就是用print()打印出来的内容)指向一个已经打开的Windows控制台窗口。

我正在用PyGame开发一个游戏,想把所有的调试信息显示在我的第二个屏幕上,那儿有一个打开的Windows终端。我知道我需要把sys.stdout改成某个东西,但我该怎么把终端窗口指向它呢?

1 个回答

0

所以,我写了这个小脚本:

import os
import sys
import time


def main():
    """
    Starts the loop check.
    """
    if len(sys.argv) == 2:

        filename = sys.argv[1]

        while True:

            # Clears the window
            os.system("cls")

            print("Tailing: ", filename)

            # Opens the file and reads the lines from it
            with open(filename) as fileToRead:

                for line in fileToRead:
                    # Gets rid of the newline at the end
                    line = line.strip("\n")
                    print(line)  # lint:ok

                # Closes the file
                fileToRead.close()

            # Waits a bit
            time.sleep(0.5)

main()

我做的就是打开一个控制台,然后用我设置了 sys.stdout 的文件来运行这个脚本。这个脚本会每0.5秒自动刷新一次,读取文件的内容。这个脚本可能需要在某些地方做一些调整,但大体上运行得很好。

撰写回答