python - How to have multiple dummy file writers in a with statement? -


i read in this answer of is possible have optional with/as statement in python? can have dummy file writer contextmanager. want, however, open multiple dummy file writers in statement context.

say create 2 dummy files: touch a , touch b.

given first part of script:

#!/usr/bin/python  contextlib import contextmanager  # file names fa="a" fb="b"  # dummy file handler none_context = contextmanager(lambda: iter([none]))() 

this addition works single dummy file writer (it prints 2):

printing=false (open(fa) if printing else none_context) writter:     print 1 if printing else 2 

this works, because indeed reading files (it prints 1):

printing=true (open(fa, "r") if printing else none_context) writter, \     (open(fb, "r") if printing else none_context) another_writter:     print 1 if printing else 2 

however, doesn't work if using 2 dummy file writers:

printing=false (open(fa, "r") if printing else none_context) writter, \     (open(fb, "r") if printing else none_context) another_writter:     print 1 if printing else 2 

it shows error:

traceback (most recent call last):   file "dummy_opener.py", line 23, in <module>     (open(fa, "r") if printing else none_context) writter, \   file "/usr/lib64/python2.7/contextlib.py", line 19, in __enter__     raise runtimeerror("generator didn't yield") runtimeerror: generator didn't yield 

why happening? , also: how can make multiple with open commands work dummy file writer?

your code fails have consumed iterator on first call, if call none_context() in block original code work:

none_context = contextmanager(lambda: iter([none])) printing=false  open(fa, "r") if printing else none_context() writter, \     open(fb, "r") if printing else none_context() another_writter:     print 1 if printing else 2 

you can see using original code if add none each open code work expected:

none_context = contextmanager(lambda: iter([none,none,none]))() printing=false  open(fa, "r") if printing else none_context writter, \     open(fb, "r") if printing else none_context another_writter,\     open(fb, "r") if printing else none_context another_writer3:     print 1 if printing else 2 

Comments

Popular posts from this blog

How to provide Authorization & Authentication using Asp.net, C#? -

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

How to use Authorization & Authentication in Asp.net, C#? -