Python 使用eval()函数时发生NameError
我试图使用另一个模块的Python 使用eval()函数时发生NameError,python,python-2.7,Python,Python 2.7,我试图使用另一个模块的eval()函数调用该模块,但在控制台输出中,我收到错误消息,如“NameError:name'Login\u CSA'未定义” 我已经写了这样的代码 在sample.py模块中 import ReferenceUnits def calling(): str='Login_CSA' eval(str) calling() 在ReferenceUnits.py中 import Login_CSA 在Login_CSA.py中我写了 def Hai()
eval()
函数调用该模块,但在控制台输出中,我收到错误消息,如“NameError:name'Login\u CSA'未定义”
我已经写了这样的代码
在sample.py模块中
import ReferenceUnits
def calling():
str='Login_CSA'
eval(str)
calling()
在ReferenceUnits.py中
import Login_CSA
在Login_CSA.py中我写了
def Hai():
print "hello this is somesh"
print 'hi welcome to Hai function'
Hai()
它正在执行,但最终得到错误消息,如“NameError:name'Login\u CSA'未定义”
为什么会这样?函数eval()
执行有效的python表达式,例如:
>>> x = 1
>>> print eval('x+1')
2
在您的例子中,eval()
函数查找根本不存在的变量Login\u CSA
,因此它返回NameError:name'Login\u CSA'未定义
函数eval()
执行有效的python表达式,例如:
>>> x = 1
>>> print eval('x+1')
2
在您的例子中,
eval()
函数查找根本不存在的变量Login\u CSA
,因此它返回NameError:name'Login\u CSA'未定义
我猜您正试图像在PHP中那样“包含并计算第二个脚本”。在Python中,当您导入文件时,所有的方法都可以在本地脚本中使用。因此,您只需从该文件中调用该方法,而不是对该文件进行eval
ing
import ReferenceUnits
import Login_CSA
def calling():
Login_CSA.Hai()
if __name__ == "__main__":
calling()
并将Login\u CSA.py
更改为
def Hai():
print "hello this is somesh"
print 'hi welcome to Hai function'
if __name__ == "__main__":
Hai()
if uuuu name uuu=“uuu main uuuuuu”:
块很重要,因为它阻止导入的脚本在导入过程中执行代码(您很少希望在导入时执行代码)。我猜您正在尝试像在PHP中那样“包含并评估第二个脚本”。在Python中,当您导入文件时,所有的方法都可以在本地脚本中使用。因此,您只需从该文件中调用该方法,而不是对该文件进行eval
ing
import ReferenceUnits
import Login_CSA
def calling():
Login_CSA.Hai()
if __name__ == "__main__":
calling()
并将Login\u CSA.py
更改为
def Hai():
print "hello this is somesh"
print 'hi welcome to Hai function'
if __name__ == "__main__":
Hai()
if uuu name uuu==“uuu main uuu”:
块很重要,因为它阻止导入的脚本在导入过程中执行代码(您很少希望在导入时执行代码)。
- 在
中导入ReferenceUnits.py
Login\u CSA
- 在
中导入sample.py
ReferenceUnits
通过使用ReferenceUnits
ReferenceUnits
使用Login\u CSA
和ReferenceUnits。Login\u CSA
使用Hai
ReferenceUnits.Login\u CSA.Hai
def calling():
str='ReferenceUnits.Login_CSA.hai'
eval(str)() # the () is essential, as otherwise, nothing gets called.
calling()
如果你
- 在
中导入ReferenceUnits.py
Login\u CSA
- 在
中导入sample.py
ReferenceUnits
通过使用ReferenceUnits
ReferenceUnits
使用Login\u CSA
和ReferenceUnits。Login\u CSA
使用Hai
ReferenceUnits.Login\u CSA.Hai
def calling():
str='ReferenceUnits.Login_CSA.hai'
eval(str)() # the () is essential, as otherwise, nothing gets called.
calling()
“(您永远不想在导入时执行代码)。”-从不有点苛刻-就像有时您所做的那样:)您导入
Login\u CSA
内部ReferenceUnits
的想法可能需要一些测试,可能函数Hai()
可以通过ReferenceUnits.Login\u CSA.Hai()
…好的。。。“非常罕见”然后:-D(你永远不想在导入时执行代码)。“-从不有点苛刻-就像有时你所做的那样:)你导入Login\u CSA
内部ReferenceUnits
的想法可能需要一些测试,也许函数Hai()
可以通过ReferenceUnits.Login\u CSA.Hai()
…好的。。。“很少”那么:-D