面向过程编程

1、实现grep -rl ‘root’ /etc功能。 

import os
def init(func):
    def wrapper(*args,**kwargs):
        g = func(*args,**kwargs)
        next(g)
        return g
    return wrapper

#阶段一:
@init
def search(target,start_path):
    while True:
        start_path = yield
        g = os.walk(start_path)
        for par_dir, _, files in g:
            for file in files:
                file_path = r'%s\%s' % (par_dir, file)
                target.send(file_path)

# 阶段二:
@init
def opener(target):
    while True:
        file_path = yield
        with open(file_path,encoding='utf-8') as f:
            target.send((file_path,f))

#阶段三:
@init
def cat(target):
    while True:
        filepath, f = yield
        for line in f:
            target.send((filepath,line))
            res = target.send((filepath,line))
            if res:
                break

#阶段四:
@init
def grep(target,pattern):
    tag = False
    while True:
        filepath,line = yield tag
        tag = False
        if pattern in line:
            target.send((filepath))
            tag = True

#阶段五:
@init
def printer():
    while True:
        filename = yield
        print(filename)



g = search(opener(cat(grep(printer(),'root'))))
print(g)
g.send(start_path)

2、一个列表嵌套很多层,用递归取出所有的值,l=[1,2,[3,[4,5,6,[7,8,[9,10,[11,12,13,[14,15]]]]]]]。

def each_list(list_name):
    for i in list_name:
        if isinstance(i,list):
            each_list(i)
        else:
            print(i,end=' ')

each_list(l)

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值