简体   繁体   中英

Python: Create list of user-defined methods from a module and referencing/calling them by user input

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?

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!')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM