When saving a data, whatever the type, what are the advantages of input over sys.stdin and / or vice versa? From what I understand, the result is the same.
When saving a data, whatever the type, what are the advantages of input over sys.stdin and / or vice versa? From what I understand, the result is the same.
The streams standards are stdin
, stdout
and stderr
, and represent files connected to the input, output and output of errors that a process has by default. Our application should not assume anything about them, or that the input is done by keyboard, or that the output goes to a terminal, ... nothing, only that they behave like text files that are read and / or write line to line.
The input
function has two tasks:
stdout
) stdin
) This behavior can be simulated in the following way:
import sys
sys.stdout.write("Dame un número:")
sys.stdout.flush()
n = sys.stdin.readline()
which is equivalent to
n = input("Dame un número:")
Obviously, it is much more convenient to use input
than standard streams (The same goes for using print
instead of stdout
). So, what's the use of streams?
As I said before, streams can be seen as files and can be exchanged with them where necessary. It is a simple system to create test batteries of code fragments. It is also used to process the output or input of child processes (something that goes out of topic).
A non-trivial example:
import sys
from io import StringIO
class WrapInput:
def __init__(self, entrada):
self.entrada = entrada
def wrapper(self, f, *args, **kw):
(sys.stdin, old_stdin) = (StringIO(self.entrada), sys.stdin)
res = f(*args,**kw)
sys.stdin = old_stdin
return res
n = WrapInput("2").wrapper(input, "Dame un número: ")
print("El número es {}".format(n))
Do not wait for you to enter the number by keyboard, read the "2"
stored in StringIO
.
Using input
or stdin
is equivalent. It's more convenient to use input
in almost any condition, but with stdin
you can do much more magic.