使用jupyter在python3中用字符串替换标准输入 [英] Replacing standard input with a string in python3 using jupyter

查看:595
本文介绍了使用jupyter在python3中用字符串替换标准输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用先前定义的字符串替换标准输入.
浏览堆栈溢出后,我发现了几种解决方案(尽管大多数是针对python2的).

I am trying to replace the standard input by a previously defined string.
After browsing on stack overflow, I found several solutions (though mostly for python2).

例如,下面的解决方案在ideone.com上进行了测试,并且似乎可以正常工作,但是当我尝试将其添加到jupyter笔记本中的代码中时,标准输入的重新定义将被忽略.

The solution below for example was tested in ideone.com and seems to work, however when I tried to add it to my code in my jupyter notebook the redefinition of the standard input gets ignored.

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

Is this due to jupyter or some problem in my code, and how could I fix it ?

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

推荐答案

简短的答案是Jupyter笔记本不支持stdin/stdout,因此您不能在笔记本代码中依赖它们.

The short answer is that Jupyter notebook doesn't support stdin/stdout, so you can't rely on them in notebook code.

更长的答案是,由于Jupyter接受输入/显示输出的方式的特殊性,在Jupyter中实现stdin/stdout的方式与在标准Python中实现方式不同.如果您想要一些可以在当前没有可用输入的情况下要求用户输入的内容,则可以这样做:

The longer answer is that stdin/stdout are implemented differently in Jupyter than in standard Python, owing to the particulars of how Jupyter accepts input/displays output. If you want something that will ask for user input if there's no input currently available, this would work:

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) 

参考

在Jupyter/IPython文档中,

stdin/stdout有点隐喻.不过,这是来自 %reset魔术的直接引述文档:

Reference

stdin/stdout is spoken of somewhat eliptically in the Jupyter/IPython docs. Here's a relevant direct quote, though, from the %reset magic docs:

从未实现标准输入的客户端(例如ipython笔记本界面)调用此方法将重置名称空间,而无需确认.

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

这篇关于使用jupyter在python3中用字符串替换标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆