Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing standard input with a string in python3 using jupyter

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) 
like image 404
Xelote Avatar asked May 20 '26 02:05

Xelote


1 Answers

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.

like image 121
tel Avatar answered May 21 '26 15:05

tel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!