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

yipeiwu_com6年前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实现制度转换(货币,温度,长度)

人民币和美元是世界上通用的两种货币之一,写一个程序进行货币间币值转换,其中: 人民币和美元间汇率固定为:1美元 = 6.78人民币。 程序可以接受人民币或美元输入,转换为美元或人民币输出...

selenium+python自动化测试之鼠标和键盘事件

selenium+python自动化测试之鼠标和键盘事件

前面的例子中,点击事件都是通过click()方法实现鼠标的点击事件。其实在WebDriver中,提供了许多鼠标操作的方法,这些操作方法都封装在ActionChains类中,包括鼠标右击、...

用python实现的线程池实例代码

python3标准库里自带线程池ThreadPoolExecutor和进程池ProcessPoolExecutor。 如果你用的是python2,那可以下载一个模块,叫threadpoo...

PyTorch中 tensor.detach() 和 tensor.data 的区别详解

PyTorch0.4中,.data 仍保留,但建议使用 .detach(), 区别在于 .data 返回和 x 的相同数据 tensor, 但不会加入到x的计算历史里,且require...

对Pytorch中nn.ModuleList 和 nn.Sequential详解

简而言之就是,nn.Sequential类似于Keras中的贯序模型,它是Module的子类,在构建数个网络层之后会自动调用forward()方法,从而有网络模型生成。而nn.Modul...