0

I am a newbie at Python and trying to write a small program to put the exeception stack to a file. Could someone let me know why the below code is not printing the whole stack into the file. :

import logging

import traceback

def divlog(x,y):
    try:
        f = open("C:/files/divlog.txt", "a")
        f.write("{0:g} / {1:g} = {2:g} \n".format(x, y , (x/y) ) )
    except ZeroDivisionError:
        #f.write("Error : \n" , traceback.format_exc())
           raise 
    finally:
        f.close()

divlog(100,21)
divlog(20,5)
divlog(10, 0)
divlog(100,spam)
1
  • 1
    You might want to consider the logging module to avoid having to open a file each time you reach a similar situation, and in general to make the logging code cleaner and more systematic. Commented Feb 19, 2014 at 2:32

4 Answers 4

2

First, your open shouldn't be inside the try..except for a ZeroDivisionError. Best solution try using a with statement instead, to automatically close the file.

with open("C:/files/divlog.txt", "a") as f:
    try:
        f.write("{0:g} / {1:g} = {2:g} \n".format(x, y , (x/y) ) )
    except ZeroDivisionError:
        f.write("Error : \n" + traceback.format_exc())  # <-- write takes 1 arg
        raise

Everything else looks right. Most likely you're getting an OSError from trying to open the file, and it's not caught by your except ZeroDivisionError

Sign up to request clarification or add additional context in comments.

Comments

1

While not really answering your question as such, you can make two very easy improvment to your code that will bypass your problem:

First, you should use the Python logging module as there should be no need to re-invent the wheel. Python comes with batteries so use them!

Second, you should consider using the with X as Y code structure for opening files:

with open(file) as fd:
    fd.write("ook")

This will ensure that the file gets closed properly.

Comments

0

Python have a module called sys, in which sys.stdout and sys.stderr can be helpful to log into another file

import logging
import sys
import traceback

f= open("C:\\AllReleases\\divlog1.txt", "a")
sys.stdout = f
sys.stderr = f
def divlog(x,y):
    try:

       f.write("{0:g} / {1:g} = {2:g} \n".format(x, y , (x/y) ) )
    except ZeroDivisionError:
       f.write("Error : \n" , traceback.format_exc())
       raise 

divlog(10, 0) divlog(100,21) divlog(20,5) divlog(100,spam)

f.close()

This will open file and write the run and error details in the given file divlog1.txt

Comments

0

This seems like exactly what the python logging module is for.

import logging
logging.basicConfig(filename='example.log',
                    level=logging.DEBUG)
logger = logging.getLogger(__name__)

def divlog(x,y):
    try:
        logger.info("{0:g} / {1:g} = {2:g} \n".format(x, y, x/y))
    except ZeroDivisionError:
        logger.exception("There was a division by zero")

def main():
    divlog(100,21)
    divlog(20,5)
    divlog(10, 0)

if __name__ == '__main__':
    main()

This gives you a file "example.log" with the following in it

INFO:__main__:100 / 21 = 4 

INFO:__main__:20 / 5 = 4 

ERROR:__main__:There was a division by zero
Traceback (most recent call last):
  File "test.py", line 8, in divlog
    logger.info("{0:g} / {1:g} = {2:g} \n".format(x, y, x/y))
ZeroDivisionError: integer division or modulo by zero

We're taking advantage of the logging.exception function to capture the traceback and log it to the file for us. Take a look at the Official HowTo for more details and examples.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.