\r\n vs \n in python eval function

喜欢而已 提交于 2019-12-07 08:40:57

问题


Why eval function doesn't work with \r\n but with \n. for example eval("for i in range(5):\r\n print 'hello'") doesn't work eval("for i in range(5):\n print 'hello'") works

I know there is not a problem cause using replace("\r","") is corrected, but someone knows why happens?

--Edit-- Oh! sorry , exactly, I meant exec. Carriage returns appeared because I'm reading from a HTML textarea via POST (I'm on a Linux box). now It is clearer, thanks to everyone.


回答1:


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;-).




回答2:


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.



来源:https://stackoverflow.com/questions/1204376/r-n-vs-n-in-python-eval-function

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