reckoner
reckoner

Reputation: 2981

direct standard error to same file and standard output?

I have something like

f=open('out.txt','w')
print >>f,  'action=%r'%action

in one of my Python programs. Is it possible to direct standard error to the same file as standard output?

Thanks!

Upvotes: 1

Views: 223

Answers (2)

philo
philo

Reputation: 3690

You might just say this:

sys.stderr = sys.stdout

But I'd wager if your script will ever be maintained by someone else, you might cause some confusion. Rather than doing this inside the script, would it be an acceptable solution to do it from the calling shell?

myscript 2>&1

Upvotes: 1

senderle
senderle

Reputation: 151097

You could do this...

import sys

f = open("error.log", "w")
sys.stderr = f            
print "raising exception"
raise Exception, "find this in error.log"

Or to answer your question more directly,

import sys
f = open("logall.txt", "w")
sys.stderr = f
sys.stdout = f
print "find this in logall.txt"
raise Exception, "find this in logall.txt"

Although I don't necessarily recommend the latter.

Upvotes: 2

Related Questions