In the Unix/Linux shell you can use backticks to capture the output of an external command. In Perl you can use both backticks and the qx operator.

In Python it requires a bit more code, but it is easy to wrap it in a function.

Basically this is it:

examples/python/qx.py

import subprocess

def qx(cmd):
   return subprocess.check_output(cmd, shell=True)

External code

In order to show how it works I've created a program (that happens to be in Python, but could be in any language) that prints to both STDOUT and STDERR:

examples/python/external.py

#!/usr/bin/env python

import sys

sys.stdout.write("Hello\n")
sys.stderr.write("Somthing to SDTERR\n")
sys.stdout.write("World\n")

If we run it we see the following on the screen:

examples/python/external.txt

Hello
Somthing to SDTERR
World

Capture using qx

examples/python/capture_stdout.py

import subprocess

def qx(cmd):
   return subprocess.check_output(cmd, shell=True)

out = qx('./external.py')

print("=={}==".format(out))

This will capture everything printed to STDOUT by the external code and assign it to the "out" variable.

Whatever printed to STDERR will be let through to STDERR.

This is the output:

examples/python/capture_stdout.txt

Somthing to SDTERR
==Hello
World
==

This is a blocking operation so your Python code will wait till the external program finishes to run.