7beggars_nnnnm
7beggars_nnnnm

Reputation: 757

Jupyter Lab - running cell forever with file.close (), print and sys.stdout

I'm not sure but I imagine that there may be issues similar to mine, but I have not found any that has been satisfactory.

When I open my Jupyter Lab and execute a cell as below (code01), it remains with the status of * (see figure01 below) meaning that it is still running the code, but the output of the out1.txt file is printed correctly. I would like to know if it is normal for the cell to remain running in this circumstances described from code01.

code01:

import sys
file = open('out1.txt', 'a')
sys.stdout = file
print("house")
file.close()

figure01:

cell running forever

Upvotes: 0

Views: 266

Answers (1)

krassowski
krassowski

Reputation: 15379

Because you redirect the stdout to a file and then close it you are breaking the IPython kernel underneath: there is no way for any stdout to be correctly processed by the kernel afterwards (cannot write to a closed file). You can reproduce it by executing your code in the IPython console rather than in a notebook. To fix this you could rebind the original stdout back:

import sys
file = open('out1.txt', 'a')
stdout = sys.stdout
sys.stdout = file
print("house")
# before close, not after!
sys.stdout = stdout
file.close()

But this is still not 100% safe; you should ideally use context managers instead:

from contextlib import redirect_stdout

with open('out1.txt', 'a') as f:
    with redirect_stdout(f):
        print('house')

But for this particular case why not to make use the file argument of the print() function?

with open('out1.txt', 'a') as f:
    print('house', file=f)

Upvotes: 1

Related Questions