如何使用子进程 popen 清除 'cmd.exe' 的 STDOUT?

How to clear the STDOUT of 'cmd.exe' with subprocess popen?

问题

下面的代码是对真实终端的模拟,在本例中是 CMD 终端。问题是“cls”不清除 CMD 的 STDOUT。因此,字符串 STDOUT 开始保持如此广泛。

问题示例

Microsoft Windows [版本 10.0.19042.746] (c) 2020 Microsoft 公司。 Todos os 直接os 保留os.

C:\Users\Lsy\PycharmProjects\Others>chdir

C:\Users\Lsy\PycharmProjects\Others

C:\Users\Lsy\PycharmProjects\Others>回声测试

测试

C:\Users\Lsy\PycharmProjects\Others>cls

类型:

问题

如何清除STDOUT?

脚本

import subprocess

f = open('output.txt', 'w')
proc = subprocess.Popen('cmd.exe', stderr=subprocess.STDOUT, stdin=subprocess.PIPE, stdout=f, shell=True)

while True:
    command = input('Type:')
    command = command.encode('utf-8') + b'\n'

    proc.stdin.write(command)
    proc.stdin.flush()
    with open('output.txt', 'r') as ff:
        print(ff.read())
        ff.close()

这不是我推荐的使用子流程的方式 - 但我假设您有某种理由以这种方式做事...

鉴于:

  1. 您已将 CMD 子进程定向到名为“output.txt”的 STDOUT 文件。
  2. CLS 字符在 output.txt.
  3. 中捕获
  4. 然后您的终端显示“output.txt”文件(从未被清除)的内容并且留下一团糟。

因此:如果你想“清除”你的子进程终端,那么你将不得不刷新你的“output.txt”文件。 您可以通过在编码之前处理“命令”变量并将其发送到子进程来简单地做到这一点。
例如:

import subprocess
import os
f = open('output.txt', 'w')
proc = subprocess.Popen('cmd.exe', stderr=subprocess.STDOUT, stdin=subprocess.PIPE, stdout=f, shell=True)
while True:
    command = input('Type:')
    if command == "cls":
        open('output.txt', 'w').close()
        os.system('cls' if os.name == 'nt' else 'clear')
    else:
        command = command.encode('utf-8') + b'\n'
        proc.stdin.write(command)
        proc.stdin.flush()
        with open('output.txt', 'r+') as ff:
            print(ff.read())

您也可以不将输出重定向到文本文件...