Mataba
Mataba

Reputation: 89

Capture the result from the terminal (external process)

I need to get the result from the terminal

mask = "audio"
a = os.system("ls -l | grep %s | awk '{ print $9 }'" % mask)
print a # a = 0, that's the exit code

#=>
file1_audio
file2_audio
0

This command just prints the result to the console, while I want to capture it to a variable.

Upvotes: 0

Views: 118

Answers (1)

Use the subprocess module

import subprocess

p = subprocess.Popen("ls -l | grep %s | awk '{ print $9 }'" % mask, 
    shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()

The shell=True is required as the pipeline is run by the shell, otherwise you get a No such file or directory.

In Python 2.7 you can also use

output = subprocess.check_output(
    "ls -l | grep %s | awk '{ print $9 }'" % mask
    stderr=subprocess.STDOUT,
    shell=True)

But I find it cumbersome to use as it throws a subprocess.CalledProcessError if the pipeline returns exit code other than 0, and to capture both stdout and stderr you need to interleave them both, which makes it unusable for many cases.

Upvotes: 4

Related Questions