3

I can't figure out how to run executable from python and after that pass it commands which is asking for one by one. All examples I found here are made through passing arguments directly when calling executable. But the executable I have needs "user input". It asks for values one by one.

Example:

subprocess.call(grid.exe)
>What grid you want create?: grid.grd
>Is it nice grid?: yes
>Is it really nice grid?: not really
>Grid created
Miro
  • 599
  • 10
  • 29
  • You could write the sequence of commands to a file, and have the executable get input from that file. – Jayanth Koushik Feb 12 '14 at 06:56
  • @Jayanth Thank you. I know how to create text file in python and write the lines in it so why not. But how I make that executable read that input (text) file? – Miro Feb 12 '14 at 07:00
  • http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx?mfr=true – Jayanth Koushik Feb 12 '14 at 07:02

1 Answers1

3

You can use subprocess and the Popen.communicate method:

import subprocess

def create_grid(*commands):
    process = subprocess.Popen(
        ['grid.exe'],
        stdout=subprocess.PIPE,
        stdin=subprocess.PIPE,
        stderr=subprocess.PIPE)

    process.communicate('\n'.join(commands) + '\n')

if __name__ == '__main__':
    create_grid('grid.grd', 'yes', 'not really')

The "communicate" method essentially passes in input, as if you were typing it in. Make sure to end each line of input with the newline character.

If you want the output from grid.exe to show up on the console, modify create_grid to look like the following:

def create_grid(*commands):
    process = subprocess.Popen(
        ['grid.exe'],
        stdin=subprocess.PIPE)

    process.communicate('\n'.join(commands) + '\n')

Caveat: I haven't fully tested my solutions, so can't confirm they work in every case.

Michael0x2a
  • 58,192
  • 30
  • 175
  • 224
  • Thank you. I have copied this and only changed the arguments to few more but I am getting error: self.stdin.write(input) TypeError: 'str' does not support the buffer interface – Miro Feb 12 '14 at 07:46
  • @Miro -- do you happen to be using Python 3, by any chance? If so, you may need to [cast the string to bytes](http://stackoverflow.com/a/5471351/646543) first before calling `communicate`. (Once again, I'm not 100% sure if that's the actual issue) – Michael0x2a Feb 12 '14 at 07:51
  • yes, PortablePython_3.2.5.1 on Windows 7. I will try that, thank you. – Miro Feb 12 '14 at 07:53
  • awesome, it works! Thank you very much. All I had to do for Python 3 was write last line as process.communicate(bytes('\n'.join(commands) + '\n', 'UTF-8')) – Miro Feb 12 '14 at 08:05