首页 > 解决方案 > 如何在 Windows 上使用 python3 执行交互式 .exe 命令

问题描述

我想用python在windows上调用一个exe。如此调用的 exe 文件在内部处理某些内容,然后提示输入,一旦输入,则提示输入另一个输入。因此,我想将提示输入保留在 python 列表中,然后调用 exe。等待提示出现,然后提供列表中的第一个字符串,然后在第二个提示中提供列表中的第二个字符串。基本上我想在 python 中创建一个函数,它能够像Windows 上的期望一样运行。

尝试了此处提供的以下代码:通过 Python 与 Windows 控制台应用程序交互,但这似乎不再适用于 Windows 10:

from subprocess import *
import re

class InteractiveCommand:
    def __init__(self, process, prompt):
        self.process = process
        self.prompt  = prompt
        self.output  = ""
        self.wait_for_prompt()

    def wait_for_prompt(self):
        while not self.prompt.search(self.output):
            c = self.process.stdout.read(1)
            if c == "":
                break
            self.output += c

        # Now we're at a prompt; clear the output buffer and return its contents
        tmp = self.output
        self.output = ""
        return tmp

    def command(self, command):
        self.process.stdin.write(command + "\n")
        return self.wait_for_prompt()

p      = Popen( ["cmd.exe"], stdin=PIPE, stdout=PIPE )
prompt = re.compile(r"^C:\\.*>", re.M)
cmd    = InteractiveCommand(p, prompt)

listing = cmd.command("dir")
cmd.command("exit")

print(listing)

有人可以帮忙吗?

标签: pythonpython-3.xwindowspython-interactive

解决方案


子进程包适用于 Windows 10。尝试以下命令。

import subprocess

p = subprocess.Popen('dir', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = p.communicate()
print(out.decode('utf-8'))

更新 您的代码在 Python 2.7 中运行良好。问题似乎出在 Python 3 上。

在此处输入图像描述


推荐阅读