Linux/Unix > Python Essential Reference, Second Edition > 9. Input and Output > Standard Input, Output, and Error | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161105084124006204201004115

### Standard Input, Output, and Error

The interpreter provides three standard file objects, known as standard input, standard output, and standard error, which are available in the `sys` module as `sys.stdin`, `sys.stdout`, and `sys.stderr`, respectively. `stdin` is a file object corresponding to the stream of input characters supplied to the interpreter. `stdout` is the file object that receives output produced by `print`. `stderr` is a file that receives error messages. More often than not, `stdin` is mapped to the user’s keyboard, while `stdout` and `stderr` produce text onscreen.

The methods described in the preceding section can be used to perform raw I/O with the user. For example, the following function reads a line of input from standard input:

    def gets():
        text = ""
        while 1:
           c = sys.stdin.read(1)
           text = text + c
           if c == '\n': break
        return text

Alternatively, the built-in function `raw_input(``prompt` `)` can read a line of text from `stdin`:

    s = raw_input("type something : ")
    print "You typed '%s'" % (s,)

Finally, keyboard interrupts (often generated by Ctrl+C) result in a `KeyboardInterrupt` exception that can be caught using an exception handler.

If necessary, the values of `sys.stdout`, `sys.stdin`, and `sys.stderr` can be replaced with other file objects, in which case the `print` statement and raw input functions use the new values. The original values of `sys.stdout`, `sys.stdin`, and `sys.stderr` at interpreter startup are also available in `sys._ _stdout_ _`, `sys._ _stdin_ _`, and `sys._ _stderr_ _`, respectively.

Note that in some cases `sys.stdin`, `sys.stdout`, and `sys.stderr` may be altered by the use of an integrated development environment (IDE). For example, when running Python under Idle, `sys.stdin` is replaced with an object that behaves like a file, but is really an object in the development environment. In this case, certain low-level methods such as `read()` and `seek()` may be unavailable.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.