Python-Ref > Basic usage > The print command > Redirecting print output
 
 

<-^^
Klíčová slova
Moduly
Knihovní funkce

Redirecting print output

Print to files or other streams instead of standard output.
By default, the print statement prints onto the standard output (stdout). This behaviour might be changed using a special syntax that redirects the output into another stream.
In the following example, we redirect some of the output into the standard error stream (stderr) that is accessible as part of the sys module.
Expand/Shrink
Zdroj: (print9.py)
  1   import sys   # we must import the sys module to give us access to the stderr stream
  2   
  3   print >> sys.stderr, "hi"  # we print this value onto the stderr
  4   print "there"              # this goes to stdout
  5   print >> sys.stderr, "."   # and this to stderr again
stdout:
there
stderr:
hi
.
Doba běhu: 20.6 ms
Redirection into open files might also be used.
Expand/Shrink
Zdroj: (print10.py)
  1   f = file( 'output.txt', 'w')   # we open a file 'output.txt' for 'w'ritting
  2   
  3   print >> f, "hi"  # this goes to 'output.txt'
  4   print "there"     # this goes to stdout
  5   print >> f, "."   # and this to 'output.txt' again
  6   
  7   
  8   f.close()   # here we close the file again
stdout:
there
hi
.
Doba běhu: 20.9 ms
For more information on reading files see Reading a file.