Ive searched the web and this site and cant find an answer to this problem. Im sure its right in front of me somewhere but cant find it.
I need to be able to import a module based on a string. Then execute a function within that module while passing arguments.
I can import based on the string and then execute using eval() but I know this is not the best way to handle this. I also cant seem to pass arguments that way.
My current module that would be set based on a string is named TestAction.py and lives in a folder called Tasks. This is the content of TestAction.py:
def doSomething(var):
print var
This is the code I am executing to import TestAction and execute.
module = "Tasks.TestAction"
import Tasks
mymod = __import__(module)
eval(module + ".doSomething()")
How can I make this code #1 not use eval()
and #2 pass the var argument to doSomething()
?
Thanks in advance!
In the module you can check dir() or similar, to see if the variable is defined. Show activity on this post. There is no such way to pass parameters to the module, however you can revamp your code a bit and import the parameters from a module as global parameters.
Use importlib to programmatically import modules The importlib provides a simple import_module function that accepts a string name with dot separators. It works just like a normal import except it uses a string to store the name. On import, the file is executed and the module object is returned.
__import__() Parameters name - the name of the module you want to import. globals and locals - determines how to interpret name. fromlist - objects or submodules that should be imported by name. level - specifies whether to use absolute or relative imports.
Thanks everyone for the help. it looks like importlib combined with getattr was what I needed. For future reference here is the exact code that is working for me.
module = "FarmTasks.TestAction"
mymod = importlib.import_module(module)
ds = getattr(mymod, "doSomething")
ds("stuff")
Is the function name also variable? If not, just use your imported module:
mymod.doSomething('the var argument')
if it is, use getattr
:
fun = 'doSomething'
getattr(mymod, fun)('the var argument')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With