O'Reilly logo

Python in a Nutshell, 2nd Edition by Alex Martelli

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Text Input and Output

Python presents non-GUI text input and output channels to your programs as file objects, so you can use the methods of file objects (covered in Attributes and Methods of File Objects) to manipulate these channels.

Standard Output and Standard Error

The sys module (covered in The sys Module) has attributes stdout and stderr, which are writeable file objects. Unless you are using shell redirection or pipes, these streams connect to the terminal running your script. Nowadays, actual terminals are rare: a so-called “terminal” is generally a screen window that supports text I/O (e.g., a Command Prompt console on Windows or an xterm window on Unix).

The distinction between sys.stdout and sys.stderr is a matter of convention. sys.stdout, known as your script’s standard output, is where your program emits results. sys.stderr, known as your script’s standard error, is where error messages go. Separating results from error messages helps you use shell redirection effectively. Python respects this convention, using sys.stderr for errors and warnings.

The print Statement

Programs that output results to standard output often need to write to sys.stdout. Python’s print statement (covered in The print Statement) can be a convenient alternative to sys.stdout.write.

print works well for the kind of informal output used during development to help you debug your code. For production output, you often need more control of formatting than print affords. You may need to control spacing, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required