【发布时间】: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