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 Section 10.3 earlier in this chapter) to manipulate these channels.
Standard Output and Standard Error
The sys
module, covered
in Chapter 8, has attributes
stdout
and stderr
, file objects
to which you can write. Unless you are using some sort of shell
redirection, these streams connect to the terminal in which your
script is running. Nowadays, actual terminals are rare: the terminal
is generally a screen window that supports text input/output (e.g.,
an MS-DOS 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 program results from error messages helps you use shell
redirection effectively. Python respects this convention, using
sys.stderr
for error and warning
messages.
The print Statement
Programs that output results to
standard output often need to write to sys.stdout
.
Python’s print
statement can be a
convenient alternative to sys.stdout.write
. The
print
statement has the following syntax:
print [>>fileobject
,]expressions
[,]
The normal destination of print
’s
output is the file or file-like object that is the value of the
stdout
attribute of the sys
module. ...
Get Python in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.