+ 1

How to feed a file as stdin to a Jupyter Notebook Python script?

Hello! I'm studying at Coursera and I'm writing my scripts in Jupyter Notebook. For submission, Coursera requires the scripts to read from stdin and write to stdout. This is easily done on command line, for example: python script.py < input.txt However, during the coding phase (ie in Jupyter), I would like to read this - say - input.txt for the script. I can't figure out how to do such redirect in Jupyter Notebook. There is just a run button, no command line argument field or anything. Any ideas?

21st Nov 2017, 9:48 AM
Jussi Rosti
Jussi Rosti - avatar
1 Resposta
+ 5
I didn't see a direct answer but these hints may get you there. For example, you can read from a docstring as if it were a file (called a "here" doc), and I've done redirection and 'inside' reading in several codes. First, Jupyter magic methods (shells, external cmds, etc) % lsmagic To suggest in the area of redirecting stdin: Redirect stdout (capture 'import this' / StringIO) https://code.sololearn.com/cV31QM0B0ozB/?ref=app Redirect stderr/stdout (symbol encoding) https://code.sololearn.com/c6NQFsmNHz82/?ref=app module "io" variables as streams (BytesIO here): https://docs.python.org/3.5/library/io.html https://code.sololearn.com/cpl25LvQ3wvu/?ref=app StringIO, bash-like "here" doc for data input: https://stackoverflow.com/questions/45414616/bash-like-heredoc-for-data-input
24th Nov 2017, 6:20 AM
Kirk Schafer
Kirk Schafer - avatar