Reputation: 5769
I'm having some issues with a simple bit of code not working correctly and I'm totally baffled as to why...
errors = open('ERROR(S).txt', 'w')
try:
execfile("AEAPER.py")
except Exception as e:
errors.write(e)
errors.close()
I get the following error:
Traceback (most recent call last):
File "C:\Sator.py", line 45, in <module>
periodically(2, -1, +1, callscripts)
File "C:\Sator.py", line 27, in periodically
s.run()
File "C:\Python27\lib\sched.py", line 117, in run
action(*argument)
File "C:\Sator.py", line 36, in callscripts
errors.write(e)
TypeError: expected a character buffer object
What is so wrong with my code and why is it doing that?
Upvotes: 0
Views: 56
Reputation: 81
The write() method expects a string as an argument. You need to convert the exception object to a string:
try:
execfile("AEAPER.py")
except Exception as e:
errors.write(str(e))
See here: http://docs.python.org/2/library/stdtypes.html#file.write
Upvotes: 1
Reputation: 365697
Unlike the print
statement, the file.write
function only takes strings. So, you just need to convert to string explicitly:
errors.write(str(e))
Of course in real-life code, you often want to do some formatting, so you often forget about this this. For example:
errors.write('Failed to exec {} with {}'.format(filename, e))
Here, we're passing the result of format
to write
, which is fine, and we're passing e
as an argument to format
, which is also fine… the fact that we've done an implicit conversion to string in the middle is easy to miss.
There are actually two different ways to represent a value as a string, str
and repr
, but str
is the one that print
uses, so it's probably what you wanted here.
Upvotes: 1
Reputation: 280335
e
isn't a string. write
needs a string. Make a string out of it with
repr(e)
or
str(e)
depending on what kind of output you want.
Upvotes: 1