Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
885 views
in Technique[技术] by (71.8m points)

python - ast.literal_eval: SyntaxError: unexpected EOF while parsing

When trying to parse an empty string I get a SyntaxError. Why does it raise a different error than parsing a 'foo'? In the source of ast.literal_eval only ValueError is explicitly raised.

In [1]: import ast

In [2]: ast.literal_eval('foo')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-d8695a7c4a9f> in <module>()
----> 1 ast.literal_eval('foo')

/usr/lib/python2.7/ast.pyc in literal_eval(node_or_string)
     78                 return left - right
     79         raise ValueError('malformed string')
---> 80     return _convert(node_or_string)
     81 
     82 

/usr/lib/python2.7/ast.pyc in _convert(node)
     77             else:
     78                 return left - right
---> 79         raise ValueError('malformed string')
     80     return _convert(node_or_string)
     81 

ValueError: malformed string

In [3]: ast.literal_eval('')
  File "<unknown>", line 0

    ^
SyntaxError: unexpected EOF while parsing
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ast uses compile to compile the source string (which must be an expression) into an AST.

If the source string is not a valid expression (like an empty string), a SyntaxError will be raised by compile. If, on the other hand, the source string would be a valid expression (e.g. a variable name like foo), compile will succeed but then literal_eval might fail with a ValueError.

Therefore, you should catch both SyntaxError and ValueError when using literal_eval.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...