need explanation
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Mon Jan 21 06:42:14 EST 2013
On Mon, 21 Jan 2013 10:06:41 -0600, kwakukwatiah wrote:
> please I need some explanation on sys.stdin and sys.stdout, and piping
> out
"stdin" and "stdout" (and also stderr) are three special, standard,
system files used by console programs that read and write text. That's
nearly all of them.
"stdin" is short for "standard input". Likewise for "standard output" and
"standard error".
When you give the Python command:
print "Hello World"
the string "Hello World" is written to stdout, which then displays it in
the console.
"stderr" is similar, except that it is used for error messages. And stdin
is used for input, rather than output.
So, in Python, I can do this:
py> import sys
py> sys.stdout.write("Hello world\n")
Hello world
But of course normally you would just use print.
Using sys.stdout, sys.stdin and sys.stderr in Python is usually
considered moderately advanced. Beginners do not usually need to care
about them.
These three special files do *not* live on the disk. There is no disk
file called "stdout" unless you create one yourself, and if you do, it
won't be special, it will just be an ordinary file with the name "stdout".
These standard files are used in Unix and Linux, and less so in Windows,
for console applications. For example, under Linux I might write this
command:
[steve at ando ~]$ touch foo
[steve at ando ~]$ ls foo
foo
The output of the `ls` command is written to stdout, which displays it on
the console. But I can *redirect* that output to a real file on disk:
[steve at ando ~]$ ls foo > /tmp/a
[steve at ando ~]$ cat /tmp/a
foo
Errors don't go to stdout, they go to stderr:
[steve at ando ~]$ ls bar > /tmp/a
ls: bar: No such file or directory
Because there is no file called "bar", the `ls` command writes an error
message to stderr. Even though I am redirecting stdout, I am not touching
stderr, so it prints to the console.
Of course there is a way to redirect stderr as well:
[steve at ando ~]$ ls bar 2> /tmp/a
[steve at ando ~]$ cat /tmp/a
ls: bar: No such file or directory
Similarly, you can redirect stdin, or you can use a pipe | to turn the
output of one command into the input of another command. This is mostly
useful when using something like command.com in Windows, not so common in
Python.
--
Steven
More information about the Python-list
mailing list