calling an external program and capturing the output

Eric ericcire at gmail.com
Sun Jan 18 13:30:14 EST 2009


Thanks guys. That helped point me int he right direction.

with your advice on the subprocess module I stumbled upon this
posting:
http://www.velocityreviews.com/forums/t359866-subprocess-module.html

for anyone else that might be interested here is the solution. It
simply calls a perl script called add.pl that reads 2 numbers from
stdin and adds them together.

Thanks again for the help.

-Eric


#!/usr/bin/env python

import subprocess

prog = "./add.pl"
args = "3 4"

app = subprocess.Popen
(prog ,stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE)

print "opened " + prog
#print app.stdout.read()

print "writing \'" + args + "\' to " + prog + " subprocess"
app.stdin.write(args)
app.stdin.write("\n")

print "wrote \'" + args + "\' to " + prog + " subprocess"
result = app.stdout.read()
result = result.rstrip('\n')

print "received: " + result



and here is the output:

./call_add.py
opened ./add.pl
writing '3 4' to ./add.pl subprocess
wrote '3 4' to ./add.pl subprocess
received: 7






More information about the Python-list mailing list