Reputation: 23
I apologize for the mess that is the title.
I'm tackling a problem in which I want to have a module in a subdirectory from my main.py. I'd like to have any number of .py files in the subdirectory. From there, I'd like to take in user input, for example the string "foo", and then search through all the methods in this module and call it if it exists. I'm looking at some sort of frankenstein combination of either dir or the inspect module, and the getattr/hasattr methods, but haven't had any luck figuring out a way that works.
inspect.getmembers(module_name, inspect.ismethod)
This returns me a large mess of pre-defined methods that I'm unsure how to sort through. If there's a better way of going about that, TYIA. Otherwise, how would I go about the situation described above?
Upvotes: 2
Views: 101
Reputation: 73490
For your concrete case, this should work. Loop through all files in your subdirectory, try to import them as modules and try to find and execute the function whose name you are given.
import importlib, os
pkg = 'some_pkg' # this must be a python package
for x in os.listdir(pkg):
try:
module = importlib.import_module(pkg + '.' + x.replace('.py', ''))
fnc = getattr(module, 'foo')
fnc()
# break in case you want to stop at the first 'foo' fnc you find
except:
print('no foo here, or not a module!')
Upvotes: 1