如何在同一命令窗口中执行命令并允许用户在每个命令后输入,同时在 Python 中打印输出?

问题描述 投票:0回答:0

我正在尝试编写一个 Python 脚本,允许用户在同一命令窗口中输入命令并显示已执行命令的输出。我写了一些几乎可以工作的代码,但是当输入为空时它会停止,并且在输入下一个命令之前不会显示当前命令的输出。

这是我正在使用的代码:

# Import the subprocess module, which allows us to spawn new processes.
import subprocess

# Start a new instance of the Windows command prompt using subprocess.Popen.
# We use stdin, stdout, and stderr pipes to communicate with the process, and 
# set the shell argument to True so that we can execute commands with shell syntax.
cmd = subprocess.Popen('cmd.exe', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

# Continuously ask the user for commands and send them to the command prompt process.
# We use a while True loop to keep the program running until the user decides to terminate it.
while True:
    # Prompt the user to enter a command.
    user_input = input("Enter a command: ")
    
    # Send the user's command to the command prompt process via stdin.
    # We encode the input as UTF-8 and add a newline character to simulate pressing Enter.
    # We then flush the stdin buffer to make sure the command is sent immediately.
    cmd.stdin.write(user_input.encode('utf-8') + b"\n")
    cmd.stdin.flush()
    
    # Read the output of the command prompt process from stdout and print it to the console.
    # We use a while True loop to read one line at a time until there is no more output.
    # We decode the output from bytes to a UTF-8 string and append each line to a list.
    # We then join all the lines into a single string and print it to the console.
    output_lines = []
    while True:
        # Read one line of output from stdout and decode it from bytes to a UTF-8 string.
        line = cmd.stdout.readline().decode('utf-8')
        
        # Check if the line is empty. If it is, there is no more output, so we break out of the loop.
        if not line:
            break
        
        # Otherwise, we append the line to a list of output lines.
        output_lines.append(line)

    # Join all the output lines into a single string and print it to the console.
    output = "\n".join(output_lines)
    if output:
        print(output)

我已经使用各种命令测试了这段代码,包括像 dir 这样的简单命令和像 ping 和 ipconfig 这样的更复杂的命令。所有命令的输出都落后于一个输入,程序也卡在所有命令的空输入上。

我在网上搜索过类似的问题,但我找到的所有解决方案都涉及为每个输入创建一个新的命令窗口。但是,我特别需要在同一个命令窗口中执行命令,并允许用户在每个命令后输入而无需打开新窗口。

python subprocess
© www.soinside.com 2019 - 2024. All rights reserved.