J Carroll
J Carroll

Reputation: 1391

Writing Pythons Errors to a txt file

I am having trouble getting this to work correctly (obviously) - I am ALMOST there, and I have a good idea of WHY it is not working - just not sure how to make it work.

This is suppose to attempt to read a file into memory, if it fails it goes to the "except" clause of the block of code (that part is 'duh'). The error file prints: "<main.DebugOutput instance at 0x04021EB8>". What I want it to do is print the actual Error. Like a FileIOError or TraceBackError or whatever it is to that error file. This is just the beginning stages and I plan to add things like date stamps and to have it append, not write/create - I just need the actual error printed to the file. Advice?

import os, sys

try:
    myPidFile = "Zeznadata.txt"
    myOpenPID_File = open(myPidFile, "r") #Attempts to open the file
    print "Sucessfully opened the file: \"" + myPidFile + "\"."

except:
    print "This file, \"" + myPidFile + "\", does not exist.  Please check the file name and try again.  "
    myFileErr = open("PIDErrorlog.txt", "w")
    myStdError = str(sys.stderr)
    myFileErr.write(myStdError)
    myFileErr.close()
    print "\nThis error was logged in the file (and stored in the directory): "

Upvotes: 1

Views: 367

Answers (5)

redpepper007
redpepper007

Reputation: 1

This will log all errors from console to a txt file. Each time the script is run, it will clear previous errors and start from scratch. If you want to save previous errors, change 'w' to 'a'. Place at the very beginning of your code:

import sys

with open('./errors.txt', 'w') as file5:  
    file5.write('')
    file5.close()

sys.stderr = open("./errors.txt", "a") 

Upvotes: 0

Lennart Regebro
Lennart Regebro

Reputation: 172249

Use the logging module. The logging module have exception formatters that will help you print exceptions in a pretty way.

http://docs.python.org/library/logging.html

Upvotes: 1

dlamotte
dlamotte

Reputation: 6385

Like Kimvais says, your problem is:

myStdError = str(sys.stderr)
myFileErr.write(myStdError)

sys.stderr is a file handle to stderr (stdout is what print writes to).

You should do something like:

try:
    ...open file...
except IOError as (errno, strerror):
    ...open errfile...
    errfile.write(strerror)
    errfile.close()

Alison's answer is also very good and well written.

Upvotes: 0

Alison R.
Alison R.

Reputation: 4294

First, you should use a logging library. It will help you deal with different logging levels (info/warn/error), timestamps and more.

http://docs.python.org/library/logging.html

Second, you need to catch the error, and then you can log details about it. This example comes from the Python documentation.

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())

except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

See how it catches an IOError and assigns the error number and error message to variables? You can have an except block for each type of error you want to deal with. In the last (generic error) block, it uses sys.exc_info()[0] to get the error details.

http://docs.python.org/tutorial/errors.html

Upvotes: 7

Kimvais
Kimvais

Reputation: 39548

the problem is here:

 myStdError = str(sys.stderr)
 myFileErr.write(myStdError)

sys.stderr is a file-like interface defined in POSIX standards, called standard error, not "error text" that you can write to a file. So what you (probably) wanted to do is:

sys.stderr = myFileErr

This is the python equivalent to python your_python_sctipt.py 2> PIDErrorLog.txt in unix shell.

Upvotes: 3

Related Questions