Skip to main content
 首页 » 编程设计

python之使用jupyter在python3中用字符串替换标准输入

2025年01月19日23xxx_UU

我正在尝试用先前定义的字符串替换标准输入。
浏览 stack overflow 后,我找到了几个解决方案(尽管主要针对 python2)。

例如,下面的解决方案已经在 ideone.com 上进行了测试并且似乎有效,但是当我尝试将其添加到我的 jupyter notebook 中的代码时,标准输入的重新定义被忽略了。

这是由于 jupyter 还是我的代码中的某些问题,我该如何解决?

import io,sys 
s = io.StringIO('Hello, world!') 
sys.stdin = s 
sys.__stdin__ = s  
r = input()  
print(r)  

请您参考如下方法:

简短的回答是 Jupyter notebook 不支持 stdin/stdout,因此您不能在 notebook 代码中依赖它们。

更长的答案是标准输入/标准输出在 Jupyter 中的实现与在标准 Python 中的实现不同,这是由于 Jupyter 如何接受输入/显示输出的特殊性。如果您想要在当前没有可用输入的情况下要求用户输入的东西,这会起作用:

import io,sys 
 
# if sys.stdin is empty, the user will be prompted for input 
# sys.stdin = io.StringIO('') 
sys.stdin = io.StringIO('Hello world') 
 
r = sys.stdin.readline() 
if not r: 
    r = builtins.input() 
 
print(r)  

引用

stdin/stdout 在 Jupyter/IPython 文档中被略微提及。不过,这是来自 %reset magic docs 的相关直接引述。 :

Calling this magic from clients that do not implement standard input, such as the ipython notebook interface, will reset the namespace without confirmation.