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

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


Use the subprocess module:

import subprocesscommand = ['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.)


This is typically a subject for a bash script that you can run in python :

#!/bin/bash# vim:ts=4:sw=4for arg; do    size=$(du -sh "$arg" | awk '{print $1}')    date=$(stat -c "%y" "$arg")    cat<<EOFSize: $sizeName: ${arg##*/}Date: $date EOFdone

Edit : How to use it : open a pseuso-terminal, then copy-paste this :

cdwget http://pastie.org/pastes/2900209/download -O info-files.bash

In python2.4 :

import osimport sysmyvar = ("/bin/bash ~/info-files.bash '{}'").format(sys.argv[1])myoutput = os.system(myvar) # myoutput variable contains the whole output from the shellprint myoutput