views:

84

answers:

4

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): "
+3  A: 

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.

Kimvais
+6  A: 

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

Alison R.
+1 for logging library, (would give another +1 for multiple `except` s)
Kimvais
Awesome - thanks for the amazing response. I've already started reading about this module/library and have been successful in using it thus far (still having a few problems with it, but I think I can "mill" through it well enough to get it working. Thank you! -j
Nascent_Notes
You'll get the best response if you post this as a new question, and show us more of your script. But barring that, it sounds like you're experiencing expected behavior. You normally wouldn't want to edit or move a log file out from under a running process. Log files are generally meant to be an archive of sorts. If your need to edit/delete the file as part of your normal workflow for this script, then maybe treating it as a log file is not the right approach. Again, it's hard to know without more information.
Alison R.
I actually figured it out: I just needed to add file.close() at the end and it was good to go! Thanks for the idea on the separate question (wasn't sure if that was kosher).
Nascent_Notes
A: 

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.

xyld
+1  A: 

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

Lennart Regebro