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

2024-10-02 12:34:29 发布

您现在位置:Python中文网/ 问答频道 /正文

问题

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

问题示例

微软视窗[versÆo 10.0.19042.746] (c) 2020年微软公司。托多斯迪雷托斯reservados

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

C:\Users\Lsy\pycharm项目\其他

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

Tags: gtcmd终端stdinstdoutprocopenusers
1条回答
网友
1楼 · 发布于 2024-10-02 12:34:29

这不是我建议使用子流程的方式-但我假设您有这样做的理由

鉴于:

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

因此:如果要“清除”子进程终端,则必须刷新“output.txt”文件。 您可以通过在编码并将其发送到子进程之前对“command”变量进行处理来完成这项工作。
e、 g:

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

您也可能无法将输出重定向到文本文件

相关问题 更多 >

    热门问题