Friday, December 18, 2009

Python's eval Function Hates Windows

(Python 2.4) I'm loading options from a file that's just a big python dict literal:
options = eval(open(argv[1]).read())
The eval function always worked when I gave it a literal string (like with """), but every time I gave it a string that was read out of a file, it would give me a syntax error on the first newline. The problem is that python's eval function can't stand '\r' characters. My line endings were windows-style, and the python interpreter didn't have a problem with them, just the eval function. Here's the solution:
options = eval(open(argv[1], "rU").read())
UPDATE: python admits this limitation for the exec function, telling you to use universal newline mode "U" when opening files for reading. However, there is no mention of this limitation in the documentation for the eval function.

No comments: