I want to execute a piece of Python code [B] from my existing Python code [A]. In B I would like to access methods defined in A. From A I would like to pass arguments to B.
If I try this way:
B.py
def Main(args):
print(args)
method_a() # this doesn't work
A.py
def method_a():
return 5
mod = importlib.import_module('B')
mod.Main(123)
Using import_module I do not have access to methods in A.py
If I use eval then I cannot pass any arguments to it and I'm not able to execute an entire file:
eval('print(123)') works
but
eval(open('B.py').read()) does not.
If I use exec I can access methods from A.py but I cannot return any value or pass any arguments. I'm Using python 3.6
import AinB.py??? And yeah, you coudl useimportlib.import_module, but that usually isn't the best, in any case though, if you did, you *definitely could use the functions inA.py. Butimportlib.import_moduleshould work.method_adoesn't work. inB.pyBut of course not, and dynamically executing code isn't going to help that.method_a()as used inB.Mainrequiresmethod_ato be in the global scope of the module. So, you could addmethod_ato the module object, but that is really not a reasonable thing to be doing. It seems like you should just change your approachmod.method_a = method_a; mod.Main(123)inA.py, instead,Maincould take the function as a parameter, that is how you should be communicating with a function from the caller. Not by hacking module namepsaces. Or again, just a re-design. Why are you trying to do it this way?