Section 10.9. Text Input and Output


10.9. 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" on page 218) to manipulate these channels.

10.9.1. Standard Output and Standard Error

The sys module (covered in "The sys Module" on page 168) 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.

10.9.2. 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" on page 61) 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, field widths, 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 "String Formatting" on page 193), then output the string, normally with the write method of the appropriate file object. (You can also pass formatted strings to print, but print adds spaces and newlines, while the write method adds nothing at all, making it easier to control exactly what gets emitted.)

When you want to direct the output from several print statements to another file, as an alternative to repeated use of the >>destination clause on each print, you can temporarily change the value of 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 and may emit results to standard output.     redirect captures those results as a string and returns a pair, with     the results string 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 

To output some text values to a file object f that aren't the current value of sys.stdout, avoid such complicated manipulations: for such simple purposes, just calling f.write is usually best, and print>>f,... is sometimes a handy alternative.

10.9.3. Standard Input

The sys module provides the stdin attribute, which is a readable file object. When you need a line of text from the user, you can call the built-in function raw_input (covered in raw_input on page 165), 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 could use built-in function input. However, input is unsuitable for most programs. Rather, 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) to let the user input any expression, as long as you totally trust the user. A malicious user can easily exploit eval to breach security and cause damage; there is no completely effective defense, except to avoid eval (and the exec statement) on any input from sources you do not fully trust. However, the following function, using some advanced introspection, may help:

 def moderately_secure_input(prompt):   s = raw_input(prompt)   c = compile(s, '<your input>', 'eval')   if c.co_names: raise SyntaxError, 'names %r not allowed'%c.co_names   return eval(c) 

This function may raise a SyntaxError exception (which you can, if you want, catch with a TRy/except statement) and doesn't let the user employ any names (thus, no built-ins, and no other functions or variables either), but otherwise accepts a wide variety of expressions and is moderately safe against abuse.

10.9.4. The getpass Module

Occasionally, 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.

getpass

getpass(prompt='Password: ')

Like raw_input, except that the text the user inputs is not echoed to the screen as the user is typing. getpass's default prompt is different from raw_input's.

getuser

getuser( )

Returns the current user's username. getuser tries to get the username as the value of one of the environment variables LOGNAME, USER, LNAME, and USERNAME, in order. If none of these variables are in os.environ, getuser asks the operating system.





Python in a Nutshell
Python in a Nutshell, Second Edition (In a Nutshell)
ISBN: 0596100469
EAN: 2147483647
Year: 2004
Pages: 192
Authors: Alex Martelli

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net