-1

I have an executable that I can run interactively from the windows command line. The workflow is as follows:

C:\Users\Me> my_executable.exe  # Running the executable from CMD

Welcome! Please choose one:
0: Exit
1: Sub-task 1
2: Sub-task 2
Enter your input: 2             # I entered this interactively

Sub-task 2 chosen.
Please choose next option:
0: Return to previous menu
1: Connect to server
2: Disconnect from server
3: Call server API 1
4: Call server API 2
Enter your input: 1             # I entered this interactively

The full workflow is complex and takes multiple passes (once through sub-task 1, then through sub-task 2 etc).

I would like to automate this using Python. I have been trying to use the subprocess module to achieve this. However, I seem to fail at the .Popen stage itself.

Here is a similar question on StackOverflow. I tried using the same approach using .Popen. This is what I see:

C:\Users\Me> python
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from subprocess import Popen, PIPE
>>> p = Popen('my-executable.exe', stdin=PIPE)
Traceback (most recent call last):
    file "<stdin>", line 1 in <module>
TypeError: unsupported operand type(s) for -:'Popen' and 'Popen'
>>> Welcome! Please choose one:
0: Exit
1: Sub-task 1
2: Sub-task 2
Enter your input: 2       # I am forced to enter this input here.
2                         # Python echoes 2 before returning to prompt
>>>                       # Back to Python prompt

Can someone help with what I am doing wrong?

Chaos
  • 466
  • 1
  • 5
  • 12
  • You might have a look at this answer using p.communicate(). https://stackoverflow.com/questions/8475290/how-do-i-write-to-a-python-subprocess-stdin – lit Sep 09 '18 at 22:11

1 Answers1

0

I don't know a proper solution, but if I may say the following.

Normally when using an external process to handle some inputs or to preform some task, all options are to be entered as in line arguments.

Like this: my-task.exe arg1 arg2...

It is a bad practice to have a sub processes that requires further input by the user.

If you are the one who wrote the exe process it's best if you rewrite it as mentioned before.

It is quite acceptable however to exchange data using proper IPC, ie. Send inputs and receive outputs. (Like using sockets)

In shot never let a sub process directly ask the user for input.

  • Unfortunately, I am not the author of the exe. I agree with your recommendation, however. The exe handles some sensitive hardware and requires quite a bit of domain knowledge in order to rewrite. As such, I am stuck with the executable. What tutorial would you recommend for IPC (maybe using sockets) that would work in Python + Windows? – Chaos Sep 09 '18 at 07:47