Jupyter Lab - 运行 cell forever with file.close (), print and sys.stdout
Jupyter Lab - running cell forever with file.close (), print and sys.stdout
我不确定,但我认为可能存在与我类似的问题,但我还没有找到令人满意的问题。
当我打开我的 Jupyter Lab 并执行如下单元格 (code01) 时,它仍然保持 *
的状态(参见 figure01 下面)意味着它仍然是 运行 代码,但是 out1.txt 文件 的输出被正确打印。
我想知道在 code01.
描述的这种情况下,单元格保持 运行 是否正常
code01:
import sys
file = open('out1.txt', 'a')
sys.stdout = file
print("house")
file.close()
图01:
因为您将 stdout 重定向到一个文件然后关闭它,您正在破坏下面的 IPython 内核:之后内核无法正确处理任何 stdout(无法写入已关闭的文件)文件)。您可以通过在 IPython 控制台而不是笔记本中执行代码来重现它。要解决此问题,您可以将原来的 stdout
重新绑定回去:
import sys
file = open('out1.txt', 'a')
stdout = sys.stdout
sys.stdout = file
print("house")
# before close, not after!
sys.stdout = stdout
file.close()
但这仍然不是 100% 安全的;理想情况下,您应该改用上下文管理器:
from contextlib import redirect_stdout
with open('out1.txt', 'a') as f:
with redirect_stdout(f):
print('house')
但是对于这种特殊情况,为什么不使用 print()
函数的 file
参数呢?
with open('out1.txt', 'a') as f:
print('house', file=f)
我不确定,但我认为可能存在与我类似的问题,但我还没有找到令人满意的问题。
当我打开我的 Jupyter Lab 并执行如下单元格 (code01) 时,它仍然保持 *
的状态(参见 figure01 下面)意味着它仍然是 运行 代码,但是 out1.txt 文件 的输出被正确打印。
我想知道在 code01.
code01:
import sys
file = open('out1.txt', 'a')
sys.stdout = file
print("house")
file.close()
图01:
因为您将 stdout 重定向到一个文件然后关闭它,您正在破坏下面的 IPython 内核:之后内核无法正确处理任何 stdout(无法写入已关闭的文件)文件)。您可以通过在 IPython 控制台而不是笔记本中执行代码来重现它。要解决此问题,您可以将原来的 stdout
重新绑定回去:
import sys
file = open('out1.txt', 'a')
stdout = sys.stdout
sys.stdout = file
print("house")
# before close, not after!
sys.stdout = stdout
file.close()
但这仍然不是 100% 安全的;理想情况下,您应该改用上下文管理器:
from contextlib import redirect_stdout
with open('out1.txt', 'a') as f:
with redirect_stdout(f):
print('house')
但是对于这种特殊情况,为什么不使用 print()
函数的 file
参数呢?
with open('out1.txt', 'a') as f:
print('house', file=f)