Python code that performs DFS search on your Linux/unix directory tree


#!/usr/bin/env python

#Parsing the Command line arguments

import argparse
parser = argparse.ArgumentParser(description=’This is an alternative Find application’)
parser.add_argument(‘-n’,’–name’, help=’Name of the file/directory string to search’,action=’store’,dest=’fname’, required=True)
parser.add_argument(‘-s’,’–start-loc’, help=’Point on directory tree from where we start looking’,action=’store’,dest=’path’, required=True)
results = parser.parse_args()

#initializations for final summary
count_file=0
count_dir=0

#pushing the first location on a stack
var=results.path
temp=var.split(‘/’,)
h=[temp[-1],var]
stack=[]
stack.append(h)
print stack

#DFS search on the directory tree
from commands import getoutput
from string import count
print ‘{0:7} {1:60} {2:70}’.format(‘Obj.’,’Directory/File name’,’Path to the file/ Directory’)
print ‘{0:7} {1:60} {2:70}’.format(‘——-‘,’—————————–‘, ‘——————————-‘)

while(len(stack)>0):
…current=stack.pop()
…list=getoutput(‘ls -l ‘+current[1])
…list=list.splitlines();
…i=1
…while(i <len(list)):
……#reporting the files
……if list[i][0]==’-‘:
………if count(list[i].split()[-1],results.fname)> 0:
…………#formatting the output
…………print ‘{0:7} {1:60} {2:70}’.format(‘File:’,list[i].split()[-1], current[1][1:])
…………count_file=count_file+1

……#reporting the directory
……if list[i][0]==’d’:
………dirname=list[i].split()[-1]
………pname=current[1]+’/’+dirname
………stack.append([dirname,pname]);
………if count(list[i].split()[-1],results.fname)>0:
…………#formatting the output
…………print ‘{0:7} {1:60} {2:70}’.format(‘Dir.:’,dirname, current[1][1:])
…………count_dir=count_dir+1

…i=i+1
# Generating the search Statistics
print “Summary:: \n —————————-”
print “Number of times the search term occured in a file name: “,count_file
print “Number of times the search term seen in directory name: “, count_dir

if count_file+count_dir >0:
…print “Total “,count_file+count_dir,” occurences are being thus reported”
else:
…print “No occurence of such a string detected on Directory tree”
#End of code

Ps:

The program implements an alternative to find comand available in Linux
usage:
./search.py -n “filename string” -s “start location of search in dir tree”
./search -h (will give a exhaustive help)

Authors:
Bipul Islam (cs1115)
Ritankar Mandal (cs1119)

NOTES:The program was written in Ubuntu 10.10 compiled on python 2.6.6 [GCC 4.4.5], modules used:argparse, string, commands
ISSUES:Due to some glitch in some version(s) of pythons,The statement: sh: Syntax error:”(” unexpected (expecting “}”) maybe outputted 4 to 5 times interleaved with actual Output

 

Advertisements