Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python subprocess output to list or file

I want to run the following bash command in Python 3:

ls -l

I know that I can do the following:

from subprocess import call
call(['ls', '-l'])

How do I save this output to a file, or put it into lists or sets?

[-rw-r--r--]  [1] [name]  [staff]   [426] [14 Jan 21:52] [HelloWorld.class]
[-rw-r--r--@] [1] [name]  [staff]   [107] [14 Jan 21:51] [HelloWorld.java]
...
etc.

I want to be able to access particular information directly, and then add it to the set, but I do not know how many items will be listed.

Any hints, snippets, or examples would really help.

like image 652
beoliver Avatar asked Jan 16 '12 13:01

beoliver


1 Answers

With >= python3.5 you can use subprocess.run:

ls_lines = subprocess.run(['ls', '-l'], stdout=PIPE).stdout.splitlines()

With >= python2.7 or >= python3.0 you can use subprocess.check_output:

ls_lines = subprocess.check_output(['ls', '-l']).splitlines()

Prior to python2.7, you need to use the lower level api, which is a bit more involved.

ls_proc = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)
ls_proc.wait()
# check return code
ls_lines = ls_proc.stdout.readlines()
like image 65
Gary van der Merwe Avatar answered Sep 21 '22 17:09

Gary van der Merwe