1. 程式人生 > >python3 面向過程編程思想,函數綜合應用

python3 面向過程編程思想,函數綜合應用

return div char pytho user turn n) filepath end

應用: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 面向過程編程思想,函數綜合應用