0

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.

10
  • What you are trying to do here could also just be done in pure Python. Commented Aug 17, 2013 at 1:31
  • @Keith, that's just an example, I have a more serious task. Commented Aug 17, 2013 at 1:31
  • Then you could use the subprocess module to run a pipeline and read the stdout. Commented Aug 17, 2013 at 1:33
  • 1
    Please read the FAQ. You are expected to have that in you question, if possible. Also, this is a common question and there are many answers to this already. Commented Aug 17, 2013 at 1:45
  • 1
    Note that if you'd just glanced at the docs for os.system they would have recommended that you use subprocess instead, and linked you straight to a section that shows exactly what you're trying to do. I don't know why you expect us to be able to explain it better than the documentation. Commented Aug 17, 2013 at 2:04

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

is there any way to get the result as an array or list instead of a string?
You have a string, isn't it good enough? stdout, stderr is a stream of bytes, not a list. If you need a list use for example stdout.splitlines()
He only really needs check_output here; there's no reason to create a Popen and call communicate unless you also have input to send it (or need to do other stuff between the creation and communicating, etc.).
Ah indeed, if he has 2.7. I always forgot that as I find it cumbersome to use, throws exceptions on nonzero exit and so forth.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.