How to run an executable from python and pass its arguments?

I can’t figure out how to run the executable from python, and after that pass commands to it that request one by one. All the examples I found here are produced by passing arguments directly when the executable is called. But the executable I need is "user input". It queries the 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
source share
1 answer

You can use the subprocessmethod Popen.communicate:

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 “communication” method essentially goes through the input, as if you were entering it. Be sure to end each line of input with a newline.

, grid.exe , create_grid, :

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

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

: , , .

+3

All Articles