使用Python实现简单Linux的find命令
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
#!/usr/bin/python #*-*coding:utf8*-* from optparse import OptionParser import os import sys #使用选项帮助信息可以使用中文 reload (sys) sys.setdefaultencoding( "utf-8" ) #定义选项以及命令使用帮助信息 usage = sys.argv[ 0 ] + " Directory Options\n\n例:" + sys.argv[ 0 ] + " /etc --type f --name passwd\n\n注意:选项和目录益可随意调换,可以写多个目录,会从多个目录中进行查找" parser = OptionParser(usage) parser.add_option( "--type" , dest = "filetype" , action = "store" , default = False , help = "指定查找对象的类型,文件类型可以是 d:代表目录 f:代表文件" ) parser.add_option( "--name" , dest = "name" , action = "store" , default = False , help = "指定查找对象的名称,文件或目录全名" ) 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) #判断目录是否存在,并且是否为目录 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 ) #判断--type选项是否正确,只能跟 f 或者 d if 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 ) |
运行结果如下:
原文链接:http://www.linuxidc.com/Linux/2017-06/144488.htm