Reputation: 87
I'm trying to call a module from another module by using the eval()
function it is calling successfully but in console output i am getting error message like "NameError: name 'Login_CSA' is not defined"
I have written the code like this
In sample.py module
import ReferenceUnits
def calling():
str='Login_CSA'
eval(str)
calling()
In ReferenceUnits.py
import Login_CSA
and in Login_CSA.py I have written
def Hai():
print "hello this is somesh"
print 'hi welcome to Hai function'
Hai()
It is executing but finally getting error message like "NameError: name 'Login_CSA' is not defined"
Why is this so?
Upvotes: 1
Views: 8589
Reputation: 91049
If you
Login_CSA
in ReferenceUnits.py
,ReferenceUnits
in sample.py
,you have to access
ReferenceUnits
by using ReferenceUnits
,Login_CSA
by using ReferenceUnits.Login_CSA
andHai
by using ReferenceUnits.Login_CSA.Hai
.So you can do
def calling():
str='ReferenceUnits.Login_CSA.hai'
eval(str)() # the () is essential, as otherwise, nothing gets called.
calling()
Upvotes: 1
Reputation: 36765
My guess is you are trying to "include and evaluate a second script" like you would do in PHP. In Python, when you import
a file, all the methods become available in your local script. So instead of eval
ing the file you would just call the method from it.
import ReferenceUnits
import Login_CSA
def calling():
Login_CSA.Hai()
if __name__ == "__main__":
calling()
and change Login_CSA.py
to
def Hai():
print "hello this is somesh"
print 'hi welcome to Hai function'
if __name__ == "__main__":
Hai()
the if __name__ == "__main__":
block is important as it prevents imported scripts from executing code during import
(you only very rarely want to execute code on import).
Upvotes: 2
Reputation: 13693
The function eval()
executes valid python expressions such as:
>>> x = 1
>>> print eval('x+1')
2
In your case the eval()
function looks for the variable Login_CSA
which simply doesn't exist, So it returns NameError: name 'Login_CSA' is not defined
Upvotes: 1