简体   繁体   English

eval函数在Python 2.7中无法正常工作

[英]eval function doen't work fine in Python 2.7

As far as I know the eval function lets a python program run python code within itself. 据我所知,eval函数可以让python程序在其内部运行python代码。

I want to run a print() command using eval function in Python2.7 , but I received the following error : 我想在Python2.7中使用eval函数运行print()命令,但收到以下错误:

>>> print "test"
test
>>> command='print "test"'
>>> command
'print "test"'
>>> eval(command)

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    eval(command)
  File "<string>", line 1
    print "test"
        ^
SyntaxError: invalid syntax
>>> 

Note that I don't have any problem with this command it python3.4 : 请注意,我对python3.4的此命令没有任何问题:

>>> print ("test")
test
>>> command='print("test")'
>>> command
'print("test")'
>>> eval(command)
test
>>> 

In Python 2 print xxx is a statement, not an expression. 在Python 2中, print xxx是语句,而不是表达式。 eval is for evaluating expressions; eval用于评估表达式; you can use exec for executing statements. 您可以使用exec执行语句。

In Python 3, print(xxx) is a function call, so it can be evaluated. 在Python 3中, print(xxx)是一个函数调用,因此可以对其进行求值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM