Code running twice - python context manager
Solution 1:
By default, print(x)
displays x
and a new line. What you see is two calls for stdout.write()
: one for x
and one for \n
.
Solution 2:
The only thing your context manager needs to do is modify stdout.write
by changing sys.stdout
itself; you don't need to make any other explicit changes, because print
already calls stdout.write
.
import sys
class MudancaDeLocal:
def __enter__ (self):
sys.stdout = open('learning.txt', 'a')
def __exit__(self,type,value, traceback):
sys.stdout.close()
sys.stdout = sys.__stdout__
sys.__stdout__
is the original value of sys.stdout
, saved just for this kind of situation.