Skip to content Skip to sidebar Skip to footer

How To Handle An Executable Requiring Interactive Responses?

I have a executable, called tsfoil2.exe, and I want to operate this .exe from my python environment. I'm running Python 2.7.3, with Spyder 2.1.11 on Windows 7. In order to operate

Solution 1:

'Press the ENTER key to exit' means that the programs expects a newline.

I see no blank line at the end of the temp file. Also, you might have meant 'I:\\\n' -- you need to use '\\' in a Python string literal if you want \ in the output.

The question is what tsfoil2.exe considers a newline e.g., b'\r\n' or just b'\n' and where it expects to receive it: from stdin (getchar()) or directly from console (getch()).

Assuming that the program expects b'\r\n' from stdin on Windows:

import os
from subprocess import CalledProcessError, Popen, PIPEcmd="tsfoil2.exe"
input_data = os.linesep.join(['I:\\', 'test', 'SC20610.inp', os.linesep])
p = Popen(cmd, stdin=PIPE, bufsize=0)
p.communicate(input_data.encode('ascii'))
if p.returncode != 0:
   raise CalledProcessError(p.returncode, cmd)

How it works

os.linesep == "\r\n" on Windows. "\n".join(["a", "b"]) == "a\nb".

Each process may have three standard streams: stdin, stdout, stderr. In Python, they are represented as sys.stdin, sys.stdout, sys.stderr. You can read input from stdin and write to stdout, stderr e.g., input function reads from stdin and print writes to stdout by default. stderr may be used to write error messages.

stdin=PIPE tells Popen to create a pipe between the parent process where it is called and the new child process ("tsfoil2.exe") and redirect the subprocess' stdin. p.communicate(data) writes data to p.stdin, closes it and waits for the child process to finish. p.returncode contains the exit status of the child process. Usually non-zero status means failure.

It emulates the shell pipeline without actually spawning the shell:

$ echo input data | tsfoil2.exe

If input is expected directly from console, you could try SendKeys module or its pure Python implementation SendKeys-ctypes:

from SendKeys import SendKeys

SendKeys(r"""
    {LWIN}
    {PAUSE .25}
    r
    C:\Path\To\tsfoil2.exe{ENTER}
    {PAUSE 1}
    I:\{ENTER}
    {PAUSE 1}
    test{ENTER}
    {PAUSE 1}
    SC20610.inp{ENTER}
    {PAUSE 1}
    {ENTER}
""")

I haven't tested it.

Post a Comment for "How To Handle An Executable Requiring Interactive Responses?"