Skip to content Skip to sidebar Skip to footer

Calling Command Exe With Python

I am trying to run a command exe from Python while passing in parameters. I have looked at a few other question, and the reason why my question is different is because I first want

Solution 1:

Take a look at subprocess communicate and pipe examples.


Solution 2:

Here is an example (first I had to create a simple python app that took some time to ask for input (6 seconds in this example) called wait.py

wait.py

import time

print "Sample Waiting App (waiting 6 seconds)"
time.sleep(6)
name = raw_input("Enter a Name: ")
print "Hello", name

Here is the code to start, wait, pass input and read output:

automator.py

from subprocess import Popen, PIPE, STDOUT

p = Popen(['python', 'wait.py'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
print p.communicate('Jason\n')[0]

And here is a break down of what is going on:

  1. subprocess.Popen() creates a process (running the python interpreter and passing the wait.py script as an argument) and assigned to p. Originally I had automator.py sleep for 10 seconds (giving the wait.py enough time to clear it's timer), but as @J.F.Sebastian pointed out this sleep is unneeded. The reason is the call to 'communicate()' will block until the wait.py is finished. Also because wait.py is reading from stdin, you can actually fill stdin will content before wait.py reads it. This is true with any application that reads from the stdin stream.
  2. Then the string 'Jason\n' is sent to the process via p.communicate('Jason\n')[0] and the output is printed. Note that stdout is showing the prompt and the output of the wait.py print statement, but not the input, this is because the input isn't in the stdout stream when you type it, it's being echoed.

Post a Comment for "Calling Command Exe With Python"