tom*_*sen 11 python file-io generator send python-3.x
如果我要用这个内容写一个文件:
#You have been defeated!
#It's merely a flesh wound!
We are the knights who say Ni!
We are the knights who say Ni!
We are the knights who say Ni!
Run Code Online (Sandbox Code Playgroud)
那么用发送器使用发送器来做它会非常非pythonic吗?我从未见过其他地方使用的发电机.
def write(file, header):
with open(file,'w') as f:
f.write(header)
line = (yield)
while True:
f.write(line)
line = (yield)
return
file='holygrail.txt'
header="#You have been defeated!\n#It's merely a flesh wound!\n"
generator = write(file,header)
generator.send(None)
for i in range(3):
generator.send('We are the knights who say Ni!\n')
generator.close()
Run Code Online (Sandbox Code Playgroud)
我问,因为上面的方法对我非常有益,而不是在contextlib堆栈中打开多个不同的文件流.如果我像这样写我的文件,我根本不必使用contextlib模块.
我之前从未问过这样的问题,我不知道它是否属于stackoverflow.
unu*_*tbu 10
我喜欢你的解决方案的创意,但我的主观意见将是使用contextlib.ExitStack()将寻找更清洁,更具可读性,比使用发电机,因为每个发电机需要与打底generator.send(None),并明确关闭.
顺便说一句,(即使我认为contextlib会导致更短,更易读的代码),write可以简化一点:
def write(file, header):
with open(file, 'w') as f:
f.write(header)
while True:
line = (yield)
f.write(line)
return
Run Code Online (Sandbox Code Playgroud)
请注意,您只需要一个line = (yield)而不是两个.
此外,generator.send(None)您可以使用coroutine装饰器代替使用您的生成器启动:
def coroutine(func):
""" http://www.python.org/dev/peps/pep-0342/ """
def wrapper(*args, **kw):
gen = func(*args, **kw)
gen.send(None)
return gen
return wrapper
Run Code Online (Sandbox Code Playgroud)
这是一个通常被理解的成语(PEP0342,David Beazley谈话),用于将发电机变成协程.所以用它装饰你的发电机也可以write达到协同广告的目的.