How to get data from command line from within a Python program?

Use the subprocess module:

import subprocess

command = ['ls', '-l']
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.IGNORE)
text = p.stdout.read()
retcode = p.wait()

Then you can do whatever you want with variable text: regular expression, splitting, etc.

The 2nd and 3rd parameters of subprocess.Popen are optional and can be removed.


The easiest way to get the output of a tool called through your Python script is to use the subprocess module in the standard library. Have a look at subprocess.check_output.

>>> subprocess.check_output("echo \"foo\"", shell=True)
'foo\n'

(If your tool gets input from untrusted sources, make sure not to use the shell=True argument.)