gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:44:42 24 4
gpt4 key购买 nike

我正在尝试用先前定义的字符串替换标准输入。
浏览 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.

关于python - 使用jupyter在python3中用字符串替换标准输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49877747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com