I am a having two python files file1.py and file2.py. I am using exec() to get the method/Variables defined in the file2.py.
file1.py have a class as given below
class one:
def __init__(self):
self.HOOK = None
exec(file2.py)
self.HOOK = Generate
### call the hook method ####
self.HOOK()
file2.py looks like as (There is no class define in file2.py)
def Generate()
do 1
do 2
hello()
def Hello()
print "hello"
Now the problem is as When i run script it is giving a error global name Hello not found. If i remove Hello() from Generate method in file2.py then its work fine. I cant use import file2.py in file1.py,because in file2.py the only one method name (Generate) is fix (its taken as requirement). So apart from Genarate method user can define any method and can call this in generate method, because this approach is not working so i have to write whole code into generate method only and code is also repetitive.
Any help is really appreciable...
3 Answers 3
Try this:
# file1.py
from file2 import Generate
class one:
def __init__(self):
self.HOOK = Generate
### call the hook method ####
self.HOOK()
In your second file:
# file2.py
def Generate():
# do 1
# do 2
hello()
def hello()
print "hello"
Comments
From what you have posted, it looks like you define a function
def hello():
print "hello"
and then tries to call another function
Hello()
Notice that python cares a lot about capital and noncapital letters.
1 Comment
You can safely write from file2 import Generate in file1.py, that will do the trick - it will import only the Generate method from file2 into the current namespace, so all the other methods the user has defined in file2 won't clutter the namespace of file1.
exec()? Usually there is a workaround.