定義:
面向過程編程思想:流水線式的編程思想,在設計程序時,需要把整個流程設計出來
優點:
1.體系結構更加清晰 (耦合度強)
2.簡化程序編程的復雜度
缺點:
1.可擴展性極其差,所以說面向過程的應用場景是:不需要經常變化的軟件
實例:
1.
import os,time
def init(func):
def wrapper(*args,**kwargs):
res = func(*args,**kwargs)
next(res)
return res
return wrapper
'''
@init
def eater(name):
print('%s start to eat'%name)
food_list = []
while True:
food = yield food_list
print('%s eat %s'%(name, food))
food_list.append(food)
'''
#過程式編程
#找到一個絕對路徑,往下一個階段發一個
@init
def search(target): ##search的參數是opener的運行結果
'找到文件的絕對路徑'
while True:
dir_name = yield
print('車間search開始生產產品:文件的絕對路徑')
time.sleep(0.2)
g = os.walk(dir_name)
for i in g:
for k in i[-1]:
file_path = '%s/%s'%(i[0], k)
target.send(file_path)
@init
def opener(target):
'打開文件獲取文件句炳'
while True:
file_path = yield
print('車間opener開始生產產品:文件句柄')
time.sleep(0.2)
with open(file_path) as f: #opener的參數是cat的運行結果
target.send((file_path, f)) #下一個階段的生成器.send 傳送
@init
def cat(target):
'讀取文件內容'
while True:
file_path,f = yield
print('車間cat開始生產產品:文件的一行內容')
time.sleep(0.2)
for line in f:
target.send((file_path,line)) #send可以傳送多個值,但必須元組類型
@init
def grep(pattern, target): #patten傳的參數
'過濾一行內容有無關鍵需要的關鍵字'
while True:
file_path,line = yield
print('車間grep開始生產產品:包含python這一行文件的絕對路徑')
time.sleep(0.2)
if pattern in line:
target.send(file_path)
@init
def printer():
'打印文件路徑'
while True:
file_path = yield
print('車間printer開始生產產品:得到最終的產品')
time.sleep(0.2)
print(file_path)
g = search(opener(cat(grep('python',printer()))))
g.send('C:\\egon')
車間search開始生產產品:文件的絕對路徑
車間opener開始生產產品:文件句柄
車間cat開始生產產品:文件的一行內容
車間grep開始生產產品:包含python這一行文件的絕對路徑
車間printer開始生產產品:得到最終的產品
C:\egon/egon.txt
車間grep開始生產產品:包含python這一行文件的絕對路徑
車間grep開始生產產品:包含python這一行文件的絕對路徑
車間opener開始生產產品:文件句柄
車間cat開始生產產品:文件的一行內容
車間grep開始生產產品:包含python這一行文件的絕對路徑
車間printer開始生產產品:得到最終的產品
C:\egon/egon1.txt
車間grep開始生產產品:包含python這一行文件的絕對路徑
車間grep開始生產產品:包含python這一行文件的絕對路徑
車間opener開始生產產品:文件句柄
車間cat開始生產產品:文件的一行內容
車間grep開始生產產品:包含python這一行文件的絕對路徑
車間grep開始生產產品:包含python這一行文件的絕對路徑
車間grep開始生產產品:包含python這一行文件的絕對路徑
車間printer開始生產產品:得到最終的產品
C:\egon\a/a.txt
車間opener開始生產產品:文件句柄
函數就是定義階段+調用階段