python 中没有输出,但在 jupyter notebook 中有输出

no output in python but output in jupyter notebook

运行以下代码

with open('abc', 'wt') as fh:
    fh.write('\n'.join(['a','b','c']))

ipython中,没有预期的输出; 然而,在 jupyter 笔记本中,输出如 [Out 4]: 5.

可能与

有关
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

在 jupyter 中。但是jupyter输出有什么奇怪的东西,如何预防呢?

我不熟悉 jupyter,但如果它是一个 REPL 打印表达式的计算结果,它会打印 fh.write 的 return 值。 write returns 写入的字符数,因此正在打印出来。

_ = fh.write 阻止输出,因为 = 是一个不求值的语句。您也可以通过 fh.write(...); None 之类的操作来阻止输出。我不建议在实际代码中这样做,但为了限制输出,这可能是有益的。