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