name = raw_input('What is your name? ') flavor = raw_input('What is your favorite ice cream flavor? ') print 'Hi, %s, I like %s too' % (name,flavor)The raw_input function writes its argument to standard output (usually the computer screen), reads a line from standard input (usually the keyboard), strips the trailing newline from the response, and returns it.
Even for more complex use of the standard streams, there is no need to explicitly open or close them; they are defined as file object attributes of the sys module with the names stdin for standard input, stderr for standard error, and stdout for standard output. Since they are defined as file objects, they can be manipulated like any other file. For example, it is often useful to read the input for a program from a file name if one is provided on a command line, or from the keyboard (standard input) if no file name is provided. The following program checks to see if a filename is given on the command line by examining the length of the argv variable of the system ]module, and then decides whether to take its input from a file or from the standard input. (See Section 8.8 for more information about argv.)
import sys if len(sys.argv) > 1: try: f = open(sys.argv[1],'r') except IOError: print >>sys.stderr, 'Error opening %s\n' % sys.argv[1] sys.exit(1) else: f = sys.stdin while 1: line = f.readline() . . .Since sys.stdin is just a file object, reading from standard input is no different than reading from any other file. Notice that the error message from the program was directed to standard error, and not standard output. When you're writing a program and you wish to produce an error message, it's a good idea to write the error message to the stderr stream rather than relying on the default behaviour of the print command (which is to write to stdout). When you use stderr, error messages will still appear on the user's screen, even if they have redirected the standard output stream to a file.
Since the sys.stdout stream is already open when you invoke python, it is not possible to pass a third argument to open (See Section 5.4) in order to make output to this stream unbuffered. If you need sys.stdout to be unbuffered (so that, for example, redirected output is written immediately instead of waiting until a buffer is filled), you can invoke python with the -u option (/u under Windows).