Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anyone give me a quick tutorial in stdin and stdout in Python 3? [closed]

Tags:

I know this sounds like something I can google, but the truth is that I don't find or do not understand what the very few Python 3 sources explains.

So here are my questions:

  • Is input() the stdin function in Python 3? Does that mean that when you open your filename.py program, the stdin is what the user types?
  • Is print() the stdout function in Python 3, or do you have to write to a file?
  • For the Spotify puzzle, is says "Input is read from stdin". What should my file include of stdin and stdout?

Update: Does that mean that i can use:

import sys
unfmtdDate = str(sys.stdin.read())

...instead of...

unfmtdDate = str(input())

?

like image 935
Martin Hallén Avatar asked Jan 24 '12 00:01

Martin Hallén


People also ask

How do I open stdin in Python?

We can use the fileinput module to read from stdin in Python. fileinput. input() reads through all the lines in the input file names specified in command-line arguments. If no argument is specified, it will read the standard input provided.


2 Answers

stdin and stdout are file-like objects provided by the OS. In general, when a program is run in an interactive session, stdin is keyboard input and stdout is the user's tty, but the shell can be used to redirect them from normal files or piped output from and input to other programs.

input() is used to prompt the user for typed input. In the case of something like a programming puzzle, it's normally assumed that stdin is redirected from a data file, and when the input format is given it's usually best to use sys.stdin.read() rather than prompting for input with input(). input() is intended for interactive user input, it can display a prompt (on sys.stdout) and use the GNU readline library (if present) to allow line editing, etc.

print() is, indeed, the most common way of writing to stdout. There's no need to do anything special to specify the output stream. print() writes to sys.stdout if no alternate file is given to it as a file= parameter.

like image 113
Wooble Avatar answered Sep 17 '22 05:09

Wooble


When you run your Python program, sys.stdin is the file object connected to standard input (STDIN), sys.stdout is the file object for standard output (STDOUT), and sys.stderr is the file object for standard error (STDERR).

Anywhere in the documentation you see references to standard input, standard output, or standard error, it is referring to these file handles. You can access them directly (sys.stdout.write(...), sys.stdin.read() etc.) or use convenience functions that use these streams, like input() and print().

For the Spotify puzzle, the easiest way to read the input would be something like this:

import sys
data = sys.stdin.read()

After these two lines the input for your program is now in the str data.

like image 25
Andrew Clark Avatar answered Sep 17 '22 05:09

Andrew Clark