Python implements the find command instance sharing in Linux, pythonfind

Source: Internet
Author: User

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:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.