import os, sys
from cStringIO import StringIO
import traceback
old_stdErr = sys.stderr
sys.stderr = mystdErr = StringIO()
try:
p = 100/0
except Exception:
traceback.print_exc(file=sys.stderr)
print mystdErr.getvalue() ### -- 1st Print statement
try:
q = 100/0
except Exception:
traceback.print_exc(file = sys.stderr)
print mystdErr.getvalue() ### -- 2nd Print statement
This piece of code .. What the output will be
Output from the 1st print statement
Traceback (most recent call last):
File “C:\Users\manojtut\Desktop\untitled-1.py”, line 9, in
p = 100/0
ZeroDivisionError: integer division or modulo by zero
Output from the 2nd print statement
Traceback (most recent call last):
File “C:\Users\manojtut\Desktop\untitled-1.py”, line 9, in
p = 100/0
ZeroDivisionError: integer division or modulo by zero
Traceback (most recent call last):
File “C:\Users\manojtut\Desktop\untitled-1.py”, line 16, in
q = 100/0
ZeroDivisionError: integer division or modulo by zero
As you can see , the exception encountered at 1st zerodivision is being printed again in the second print statement which I don’t want. Can I somehow eliminate/flush away the first exception traceback so that only the second exception’s traceback can be printed in the second print statement?
Add this:
before the second block.
resetresets the file position to the beginning and writing begins from there.truncateremoves all data after the current position. If ‘truncate’ is omitted – the data in the stream will be overwritten from subsequent writes.