qx or backticks in python - capture the output of external programs
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.
qxx - capture both stdout and stderr
examples/python/qxx.py
import subprocess def qxx(cmd): proc = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.STDOUT, shell = True, ) stdout, stderr = proc.communicate() if proc.returncode != 0: raise Exception("Error executing {}".formart(cmd)) return stdout
See also
examples/python/capture.py
import subprocess import sys def run(cmd): proc = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE, ) stdout, stderr = proc.communicate() return proc.returncode, stdout, stderr code, out, err = run([sys.executable, 'examples/python/run.py']) print("out: '{}'".format(out)) print("err: '{}'".format(err)) print("exit: {}".format(code))
capture STDOUT, STDERR, and exit in python.
Published on 2019-05-17