码迷,mamicode.com
首页 > 编程语言 > 详细

python3 面向过程编程思想,函数综合应用

时间:2017-06-22 22:21:15      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:project   yield   ret   start   open   walk   filename   return   for   

应用: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):
    ‘search file abspath‘
    while True:
        start_path=yield
        g = os.walk(start_path)
        for par_dir, _, files in g:
            # print(par_dir,files)
            for file in files:
                file_path = r‘%s\%s‘ % (par_dir, file)
                target.send(file_path)
#阶段二:收到文件路径,打开文件获取获取对象,把文件对象发给阶段三
@init
def opener(target):
    ‘get file obj: f=open(filepath)‘
    while True:
        file_path=yield
        with open(file_path,encoding=‘utf-8‘) as f:
            target.send((file_path,f))

#阶段三:收到文件对象,for循环读取文件的每一行内容,把每一行内容发给阶段四
@init
def cat(target):
    ‘read file‘
    while True:
        filepath,f=yield
        for line in f:
            res=target.send((filepath,line))
            if res:
                break

#阶段四:收到一行内容,判断root是否在这一行中,如果在,则把文件名发给阶段五
@init
def grep(target,pattern):
    ‘grep function‘
    tag=False
    while True:
        filepath,line=yield tag #target.send((filepath,line))
        tag=False
        if pattern in line:
            target.send(filepath)
            tag=True
#阶段五:收到文件名,打印结果
@init
def printer():
    ‘print function‘
    while True:
        filename=yield
        print(filename)

start_path1=r‘C:\Users\Administrator\PycharmProjects\python5期\a‘
start_path2=r‘C:\Users\Administrator\PycharmProjects\python5期\a\b‘
g=search(opener(cat(grep(printer(),‘root‘))))

print(g)
# g.send(start_path1)
g.send(start_path2)

  

python3 面向过程编程思想,函数综合应用

标签:project   yield   ret   start   open   walk   filename   return   for   

原文地址:http://www.cnblogs.com/lucaq/p/7067452.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!