#!/usr/bin/python
#coding=utf-8

import sys,os,time

sep = os.path.sep
result_file = 'result.txt'

def walk_dir(dir_name='/'):
    '''
    根据目录名遍历目录中所有的文件和目录
    '''
    export = ""
    dirs_num = 0
    file_num = 0
    print "开始建立目录树:"
    start_time = time.time()
    for root,dirs,files in os.walk(dir_name):
        for dir in dirs:
            tmp_dir = 'dir: ' + os.path.join(root, dir) + '\n'
            export += tmp_dir
            print tmp_dir
            dirs_num += 1
        for file in files:
            tmp_file = 'file: ' + os.path.join(root, file) + '\n'
            export += tmp_file
            print tmp_file
            file_num += 1
    open(result_file, 'w').write(export)
    end_time = time.time()
    used_time = end_time - start_time
    print "成功建立目录树"
    print "耗时："  + str(used_time) + "秒"

def find_file(dir_name='/', file_name=''):
    if file_name == '':
        print 'please enter find file_name'
        return False
    walk_dir(dir_name)
    start_time = time.time()
    print '\n\n start find file %s'%(file_name)
    for eachline in open(result_file, 'r').readlines():
        if eachline.find(file_name) != -1:
            print eachline
    end_time = time.time()
    used_time = end_time - start_time
    print 'used time: ' + str(used_time)
    print 'find  finish'
    sys.exit()

def usage():
    print '''
Usage:
    --walk_dir
        python walk_dir.py --walk_dir dir_name
    --find_file
        python walk_dir.py --find_file  file_name [dir_name]
    
    '''

if __name__ == "__main__":
    if len(sys.argv) < 2:
        usage()
        exit(-1)
    try:
        if sys.argv[1] == '--walk_dir':
            walk_dir(sys.argv[2])
        elif sys.argv[1] == '--find_file':
            find_file(file_name = sys.argv[2], dir_name = sys.argv[3])
        else:
            usage()
            exit(-1)
    except Exception, e:
        print e


