Reputation: 134
I have some modules like this:
Drivers/
a.py
b.py
c.py
Now I want to call them on the basis of a variable value. let us consider driver is the variable from where I will get the variable name.
if driver=='a':
#then call the driver a and execute.
a.somefunction()
if driver=='b':
#then call the driver b and execute
I know the value we get from the driver in if statement is a string type value and in the if statement we have to call a module. is there any way to convert it.??
Upvotes: 3
Views: 134
Reputation: 6186
If the modules are in the same level(exactly your case), just
module = __import__(driver)
module.somefunction()
driver
can be string
such as 'a'
, 'b'
, or 'c'
. If the module does not exist, ImportError
is raised.
Upvotes: 2
Reputation: 7255
Or you can use this:
import imp
py_mod = imp.load_module(driver, *imp.find_module(driver, ['Drivers']))
Upvotes: 0
Reputation: 81
You should read here about module search path: https://docs.python.org/2/tutorial/modules.html#the-module-search-path
this discussion shows how to convert string to command: http://www.daniweb.com/software-development/python/threads/198082/converting-string-to-python-code
Basic example for your case would be something like:
assuming a and b are directories in linux in the root
import sys
import os
if driver=='a':
# add /a to the module search path
sys.path.append(os.path.join(['/', driver]))
command_string = 'import ' + driver + '.py'
# converts a string to python command
exec(command_string)
#then call the driver a and execute.
a.somefunction()
if driver=='b':
sys.path.append(os.path.join(['/', driver]))
command_string = 'import ' + driver + '.py'
# converts a string to python command
exec(command_string)
#then call the driver b and execute
Upvotes: 0
Reputation: 174624
Here is another approach:
def default_action():
print('I will do this by default')
return 42
the_function = default_action
if driver == 'a':
from a import somefunction as the_function
if driver == 'b':
from b import some_other_function as the_function
if driver == 'c':
from c import some_other_function as the_function
print('Running the code ... ')
result = the_function()
print('Result is: {}'.format(result))
You'll have to make sure that the full path to Drivers/
is in your PYTHONPATH
variable.
Upvotes: 1
Reputation: 42758
If your "Drivers/" directory in the searchpath of python, simply import the module and call the function:
import importlib
module = importlib.import_module(driver)
module.some_function()
Upvotes: 5