Rohit Sharma
Rohit Sharma

Reputation: 382

How to save the output of a linux command in dictionary?

I am trying to get list of all files and there modification time in a key to value pair.

I've tried to store the output by using subprocess.check_output("ls -lh | grep -v '^d' | awk '{print $9,$8}'", shell=True ) but as it is returning me bytes I am not able to convert that in to dictionary.

text = subprocess.check_output("ls -lh | grep -v '^d' | awk '{print $9,$8}'", shell=True)

Upvotes: 0

Views: 1171

Answers (2)

DeepSpace
DeepSpace

Reputation: 81594

First call .decode() on the output so you will work with a string. Then you will have to do some strip and split magic to construct the dictionary:

import subprocess

output = subprocess.check_output("ls -lh | grep -v '^d' | awk '{print $9,$8}'", shell=True).decode()

d = {}
for line in output.split('\n'):
    line = line.strip()
    if line:
        file_name, mod_time = line.split()
        d[file_name] = mod_time 

print(d)

Upvotes: 1

Erdal Dogan
Erdal Dogan

Reputation: 617

Use .decode() method to convert from bytes to string. Such as:

text = subprocess.check_output("ls -lh | grep -v '^d' | awk '{print $9,$8}'", shell=True).decode('utf-8')

I assume you'll handle the rest from here?

Upvotes: 0

Related Questions