10.7 Text Input and OutputPython 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. 10.7.1 Standard Output and Standard ErrorThe 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. 10.7.2 The print StatementPrograms 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. However, when >>fileobject, is present right after keyword print, the statement uses the given fileobject instead of sys.stdout. expressions is a list of zero or more expressions separated by commas (,). print outputs each expression, in order, as a string (using the built-in str, covered in Chapter 8), with a space to separate strings. After all expressions, print by default outputs '\n' to terminate the line. When a trailing comma is present at the end of the statement, however, print does not output the closing '\n'. 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, field widths, the number of decimals for floating-point values, and so on. In this case, prepare the output as a string with the string-formatting operator % covered in Chapter 9. Then, you can output the resulting string, normally with the write method of the appropriate file object. When you want to direct print's output to another file, you can temporarily change sys.stdout. The following example shows a general-purpose redirection function that you can use for such a temporary change: def redirect(func, *args, **kwds): """redirect(func, ...) -> (output string result, func's return value) func must be a callable that outputs results to standard output. redirect captures those results in memory and returns a pair, with the results as the first item and func's return value as the second one. """ import sys, cStringIO save_out = sys.stdout sys.stdout = cStringIO.StringIO( ) try: retval = func(*args, **kwds) return sys.stdout.getvalue( ), retval finally: sys.stdout.close( ) sys.stdout = save_out When all you want is to output some text values to a file object f that isn't the current value of sys.stdout, you won't normally perform complicated manipulations as shown in the previous example. Rather, for such simple purposes, just calling f.write is usually best. 10.7.3 Standard InputThe sys module provides the stdin attribute, which is a file object from which you can read text. When you need a line of text from the user, call the built-in function raw_input (covered in Chapter 8), optionally with a string argument to use as a prompt. When the input you need is not a string (for example, when you need a number), you can use built-in function input. However, input is unsuitable for most programs. More often, you use raw_input to obtain a string from the user, then other built-ins, such as int or float, to get a number from the string. You can also use eval (normally preceded by compile, for better control of error diagnostics), as long as you trust the user totally. A malicious user can easily exploit eval to breach security and cause damage. When you do have to use eval on untrusted input, be sure to use the restricted-execution tools covered in Chapter 13. 10.7.4 The getpass ModuleOccasionally, you want the user to input a line of text in such a way that somebody looking at the screen cannot see what the user is typing. This often occurs when you're asking the user for a password. The getpass module provides the following functions.
Like raw_input, except that the line of text the user inputs in response is not echoed to the screen while the user is typing it. Also, getpass's default prompt is different from raw_input's.
Returns the current user's username. First, getuser tries to get the username as the value of one of environment variables LOGNAME, USER, LNAME, and USERNAME, in this order. If none of these variables are keys in os.environ, getuser tries asking the operating system for the username. |