Python实现Linux的find命令实例分享

yipeiwu_com5年前Python基础

使用Python实现简单Linux的find命令

代码如下:

#!/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)

运行结果如下:

相关文章

Python学生信息管理系统修改版

在学习之前先要了解sqlite游标的使用方法python使用sqlite3时游标的使用方法 继上篇博客Python实现学生信息管理系统后,我就觉得写的太复杂了,然后又是一通优化、优化...

详解Python中正则匹配TAB及空格的小技巧

在正则中,使用.*可以匹配所有字符,其中.代表除\n外的任意字符,*代表0-无穷个,比如说要分别匹配某个目录下的子目录: >>> import re >>...

python中的break、continue、exit()、pass全面解析

1、break break是终止本次循环,比如你很多个while循环,你在其中一个while循环里写了一个break,满足条件,只会终止这个while里面的循环,程序会跳到上一层whil...

Python 获取numpy.array索引值的实例

举个例子: q=[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15] 我想获取其中值等于7的那个值的下标,以便于用于其他计算。 如果使用np.where,...

详解Python的数据库操作(pymysql)

使用原生SQL语句进行对数据库操作,可完成数据库表的建立和删除,及数据表内容的增删改查操作等。其可操作性很强,如可以直接使用“show databases”、“show tables”等...