I want to invoke an exe on windows with python. The exe file so invoked processes something internally and then prompts for an input and once this is entered prompts for another input. Therefore, I want to keep the prompt inputs in a python list and then invoke the exe. Wait for the prompt to appear and then provide the first string in list and then provide the second string in list on second prompt. Basically I want to create a function in python that is able to act like expect on windows.
Tried the below code provided here: Interact with a Windows console application via Python, but this doesn't seem to work anymore with 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)
Could someone please help?
Subprocess package works fine with Windows 10. Try the following commands.
Update Your code runs fine in Python 2.7. The problem seems to be with Python 3.