stdout to file

Gerrit Holl gerrit.holl at pobox.com
Fri Dec 10 10:42:51 EST 1999


16:39:35:1/501:gerrit at stopcontact:~$ python /usr/doc/packages/python/Tools/world/world pc
Where in the world is pc?

Sposhua wrote:
> Right, useless newbie question here...

Never useless! *you* can learn from it!

> Is there any point to using:
> 
> file = open("inquisition.txt","w")
> file.write("Nobody expected it.\n")
> file.close()
> 
> ...when this seems more efficient and closer to the shell:
> 
> import sys
> sys.stout = open("inquisition.txt","w")
> print "Nobody expected it.\n"
> 
> Are there occasions to use one instead of the other? Is #2 really more
> efficient?

I don't think #2 is more efficient, but it's IMHO less readable. If you
use #2, and one skims the code quickly, it sees "print ..." and wonders:
"Why don't I see it?", but when one sees 'file.write("...")', it's much
more clear. I far prefer #1.

> Also, in #2, do you have to "close" stdout (and if so how,
> sys.stout.close()?) and how do you reset stdout to the screen (.close()
> again?).

>>> sys.stdout = sys.__stdout__

You can use sys.__stdout__ for it. You can also copy sys.__stdout__, I don't
know difference, a copy function for a fp is in os or os.path.

> PS, I'm sending this in Outlook, which I don't know very well. Does it look
> ok in Pine and other text-only mailers? Do the lines wrap at 70(ish)
> characters?

The lines wrap OK.

regards,
Gerrit.

-- 
"The move was on to 'Free the Lizard'"

  -- Jim Hamerly and Tom Paquin (Open Sources, 1999 O'Reilly and Associates)
  4:40pm  up  1:07, 16 users,  load average: 1.25, 1.26, 1.26




More information about the Python-list mailing list