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
One way to access to the information in ls -l output is to parse it. For example, csv.DictReader could be use to map each column to a field in a dictionary:
import subprocess
import csv
process = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)
stdout, stderr = process.communicate()
reader = csv.DictReader(stdout.decode('ascii').splitlines(),
delimiter=' ', skipinitialspace=True,
fieldnames=['permissions', 'links',
'owner', 'group', 'size',
'date', 'time', 'name'])
for row in reader:
print(row)
The code above will print a dictionary for each line in ls -l output such as:
{'group': '',
'name': '',
'links': '1',
'date': '',
'time': '',
'owner': '',
'permissions': '-rw-rw-r--',
'size': ''}