views:

52

answers:

3

I would like to call an external script from within a function, for instance:

import subprocess

def call_script(script):
   subprocess.call(script)
   return answer #retrieving the result is the part I'm struggling with

call_script("/user/bin/calc_delta.py")

The script calc_delta.py simply prints the result when it is done. How can I assign the result of that script to a variable? Thank you.

+2  A: 

You should look at subprocess.Popen (popen)

For instance (from the docs):

pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE).stdout

subprocess.call is only going to give you the response code for your call, not the output.

sberry2A
+4  A: 

Instead of using subprocess.call you should use Popen and call communicate on it.

That will allow you to read stdout and stderr. You can also input data with stdin.

Example from the docs http://docs.python.org/library/subprocess.html#replacing-bin-sh-shell-backquote:

output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
WoLpH
+3  A: 

In Python ≥2.7 / ≥3.1, you could use subprocess.check_output to convert the stdout into a str.

answer = subprocess.check_output(['/usr/bin/calc_delta.py'])

There are also subprocess.getstatusoutput and subprocess.getoutput on Python ≥3.1 if what you need is a shell command, but it is supported on *NIX only.

KennyTM