\\r\\n vs \\n in python eval function

三世轮回 提交于 2019-12-05 14:05:33

You have a strange definition of "work":

>>> eval("for i in range(5):\n print 'hello'")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(5):
      ^
SyntaxError: invalid syntax
>>> 

I'm not sure why you're using eval -- I suspect you mean exec. Expressions and statements are drastically different entities in Python -- eval only deals with expressions (a bare expression is also a statement, so exec can deal with it as well as other statements).

Turning to exec, and pondering the situation as a Python core committer, I think it's a minor mis-design: just like (redundant and useless) spaces, tabs and form feeds just before a NEWLINE are accepted and ignored, so should (just as redundant and useless) carriage returns be. I apologize: I think we never ever considered that somebody might want to put carriage returns there -- but then, it doesn't make any more sense to have e.g. form feeds there, and we do accept that... so I see no rationale for rejecting carriage returns (or other Unicode non-ANSI whitespace, either, now that in Python 3 we accept arbitrary Unicode non-ANSI alphanumerics in identifiers).

If you care, please open an issue on Python's issue tracker, and (barring unforeseen opposition by other commiters) I think I can get it fixed by Python 3.2 (which should be out in 12 to 18 months -- that's an estimate [informed guess], not a promise;-).

Do you mean eval or exec? Please post exactly what you ran, plus the full traceback and error message.

The problem is probably because the Python grammar says that lines are terminated by newlines ('\n'), not the two-character sequence '\r\n'.

In general, it would be safer for you to use replace('\r\n', '\n') in case there's a meaningful '\r' in there somewhere. It would be better if you didn't have the '\r' there in the first place ... how are you obtaining the text -- binary read on a Windows box??

Talking about safety, you should be careful about using eval or exec on any old code obtained from a possible enemy.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!