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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With