Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to create a "runner" script in Python?

I have a bunch of Python modules in a directory, all being a derivate class. I need a "runner" script that, for each module, instantiate the class that is inside it (the actual class name can be built by the module file name) and than call the "go" method on each of them.

I don't know how many modules are there, but I can list all of them globbing the directory via something like "bot_*.py"

I think this is something about "meta programming", but how could be the best (most elegant) way to do it?

like image 486
Claudio Avatar asked Jul 16 '26 23:07

Claudio


2 Answers

You could use __import__() to load each module, use dir() to find all objects in each module, find all objects which are classes, instantiate them, and run the go() method:

import types
for module_name in list_of_modules_to_load:
    module = __import__(module_name)
    for name in dir(module):
        object = module.__dict__[name]
        if type(object) == types.ClassType:
            object().go()
like image 151
Adam Rosenfield Avatar answered Jul 19 '26 13:07

Adam Rosenfield


def run_all(path):
    import glob, os
    print "Exploring %s" % path
    for filename in glob.glob(path + "/*.py"):
        # modulename = "bot_paperino"
        modulename = os.path.splitext(os.path.split(filename)[-1])[0]
        # classname = "Paperino"
        classname = modulename.split("bot_")[-1].capitalize()
        # package = "path.bot_paperino"
        package = filename.replace("\\", "/").replace("/", ".")[:-3]
        mod = __import__(package)
        if classname in mod.__dict__[modulename].__dict__.keys():
            obj = mod.__dict__[modulename].__dict__[classname]()
            if hasattr(obj, "go"):
                obj.go()

if __name__ == "__main__":
    import sys
    # Run on each directory passed on command line
    for path in sys.argv[1:]:
        run_all(sys.argv[1])

You need a __init__.py in each path you want to "run". Change "bot_" at your will. Run on windows and linux.

like image 34
Marcob Avatar answered Jul 19 '26 13:07

Marcob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!