【问题标题】:How to execute interactive .exe command with python3 on Windows如何在 Windows 上使用 python3 执行交互式 .exe 命令
【发布时间】:2020-10-04 17:22:34
【问题描述】:

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

尝试了此处提供的以下代码:Interact with a Windows console application via Python,但这似乎不再适用于 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)

有人可以帮忙吗?

【问题讨论】:

  • 您正在运行的程序 (vpnclient.exe) 在写入管道时可能会缓冲其输出。在 Windows 中没有常见的解决方法。它可能有一个命令行选项来强制不缓冲或行缓冲。否则你必须发挥创造力。
  • 如果您仅在 Windows 10 的更新安装上运行,您可以创建一个伪控制台会话 (ConPTY),让您可以直接读取和写入孩子的控制台会话。但是 ConPTY 相对较新,Python 的标准库还没有对它的任何支持。它需要大量使用 ctypes、CFFI 或 C 扩展模块。
  • 使用 wexpect 包,用 pip (wexpect.readthedocs.io/en/latest) 安装

标签: python python-3.x windows python-interactive


【解决方案1】:

Subprocess 包在 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 上。

【讨论】:

  • 我正在调用 exe 而不是“dir”。例如vpnclient.exe。一旦调用它,它会提示输入用户名和密码。我需要一种方法来等待提示出现并传递相应的输入。如果我们可以流式传输输出,或者至少一旦建立连接,脚本就应该退出。
猜你喜欢
  • 1970-01-01
  • 2012-02-20
  • 1970-01-01
  • 2019-02-13
  • 2019-06-22
  • 1970-01-01
  • 2019-05-25
  • 2023-02-21
  • 1970-01-01
相关资源
最近更新 更多