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
3
  • You could write the sequence of commands to a file, and have the executable get input from that file. Commented Feb 12, 2014 at 6: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? Commented Feb 12, 2014 at 7:00
  • microsoft.com/resources/documentation/windows/xp/all/proddocs/… Commented Feb 12, 2014 at 7:02

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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 -- do you happen to be using Python 3, by any chance? If so, you may need to cast the string to bytes first before calling communicate. (Once again, I'm not 100% sure if that's the actual issue)
yes, PortablePython_3.2.5.1 on Windows 7. I will try that, thank you.
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'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.