0

I'm new to Python, and I'm given an engine in bash (which takes its own unique commands from a command line prompt or a file and exercises a specific functionality). I want to subprocess it through Python.

I'm able to open the engine with subprocess.call(path, shell=True), and manually interact with it / input commands, but I cannot figure out how to script the unique commands to input into the engine through Python, to see the outputs automatically. I've tried to understand all of the documentation, but it is so, so verbose.

Ideally I would like to script all of my input commands in Python, subprocess the engine, and see the output from my engine in the Python output.

Again, forgive me if this sounds confusing. For example, I've tried:

p = subprocess.Popen(path-to-engine, stdin = subprocess.PIPE, stdout = subprocess.PIPE, shell=True)
p.stdin.write("some commands")
p.stdout.readline()
p.kill()

but this just gives me exit code 0, and no output.

Hai Vu
  • 37,849
  • 11
  • 66
  • 93
boldbrandywine
  • 322
  • 1
  • 14

1 Answers1

0

You should use .communicate() instead of .kill():

import subprocess
p = subprocess.Popen(
    path_to_engine,
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    shell=True)
p.stdin.write("some commands\n")
stdout, stderr = p.communicate()

print('stdout:')
print(stdout)
print('stderr:')
print(stderr)
Hai Vu
  • 37,849
  • 11
  • 66
  • 93
  • Thanks for your answer; however, it seems the process is getting hung up after `p.communicate()` – boldbrandywine Jun 03 '16 at 17:06
  • @boldbrandywine: 1- pass the input using `input` parameter: `p.communicate(input="some command")` 2- `p.communicate()` waits for the child process to exit i.e., don't use it if you want to pass a dynamic input that depends on the answers from the subprocess. You probably want [`pexpect` module in this case](http://stackoverflow.com/q/7897202/4279) – jfs Jun 04 '16 at 19:49