【问题标题】:How to clear the STDOUT of 'cmd.exe' with subprocess popen?如何在子进程弹出的情况下清除“cmd.exe”的 STDOUT?
【发布时间】:2021-05-10 02:36:26
【问题描述】:

问题

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

问题示例

Microsoft Windows [版本 10.0.19042.746] (c) 2020 年微软公司。 Todos os direitos reservados。

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()

【问题讨论】:

  • 你从不在任何地方使用cls?!
  • 我确实举了一个“cls”问题的例子。基本上,如果您键入一些命令并尝试使用 'cls' 来清除它不起作用。

标签: python subprocess popen


【解决方案1】:

这不是我推荐使用子流程的方式 - 但我假设你有一些理由这样做......

给定:

  1. 您已将 CMD 子进程定向到 STDOUT 到名为“output.txt”的文件。
  2. 在 output.txt 中捕获了 CLS 字符。
  3. 然后您的终端显示“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())

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多