Python implements the find command instance sharing in Linux, pythonfind
Use Python to implement the find command in Linux
The Code is as follows:
#! /Usr/bin/python # *-* coding: utf8 *-* from optparse import OptionParserimport osimport sys # use the option help information to use the Chinese reload (sys) sys. setdefaultencoding ("UTF-8") # define options and command usage help information usage = sys. argv [0] + "Directory Options \ n example:" + sys. argv [0] + "/etc -- type f -- name passwd \ n Note: Options and directories can be freely exchanged and multiple directories can be written, searches for "parser = OptionParser (usage) parser from multiple directories. add_option ("-- type", dest = "filetype", action = "store", default = False, help = "specifies the type of the object to be searched. The file type can be d: directory f: file ") parser. add_option ("-- name", dest = "name", action = "store", default = False, help = "specify the name of the object to be searched, full name of the file or directory") options, args = parser. parse_args () def find (dir): directory = OS. walk (dir) for x, y, z in directory: if options. filetype = "f": for name in z: if name = options. name: path = OS. path. join (x, name) print (path) if options. filetype = "d": for name in y: if name = options. name: path = OS. path. join (x, name) print (path) # determine whether the directory exists and whether it is a directory for dir in args: if OS. path. exists (dir) = False: sys. stderr. write (dir + "is not found \ n") exit (100) if OS. path. isfile (dir): sys. stderr. write (dir + "is a file \ n") exit (101) # determine whether the -- type option is correct. It can only be used with f or dif not (options. filetype = "f" or options. filetype = "d"): sys. stderr. write ("-- type only support d or f \ n") exit (102) if _ name _ = "_ main _": for dir in args: find (dir)
The running result is as follows: