Monday, August 22, 2016

combine command ls with file

file command is used to view file type and ls is used to list directory with many options available. so if they work together, that would be better, so the following is the script to combine the two utilities, it is not the optimal, but it works


import os
import sys
import subprocess
import re

directory = sys.argv[1]

ldir = os.listdir(directory)

dicttype = {}
for i in ldir:

    command1 = ["file", i]
    filetype = subprocess.Popen(command1 ,stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    fr = filetype.stdout.read()
    if fr == "":
        continue
    frl = fr.split(": ")

    dicttype[frl[0]] = frl[1].split()[0]


lsoption = sys.argv[1:]
lscommand = ["ls"] + lsoption
lsout = subprocess.Popen(lscommand ,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
fr = lsout.stdout.read()
frl = fr.split("\n")
for i in frl:
    for j in dicttype.keys():
        if re.search(j, i):
            print i + " ... " + dicttype[j]
            break



#####################
usage: python print-filesize-type.py directory_name ls-arguements 

example:


No comments:

Post a Comment