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:
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?print()
the stdout
function in Python 3, or do you have to write to a file?stdin
and stdout
?Update: Does that mean that i can use:
import sys
unfmtdDate = str(sys.stdin.read())
...instead of...
unfmtdDate = str(input())
?
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With