Replacing standard input with a string in python3

2019-07-14 03:20发布

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).

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.

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) 

1条回答
等我变得足够好
2楼-- · 2019-07-14 04:02

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

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) 

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:

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

查看更多
登录 后发表回答