Best way to create a “runner” script in Python?

I have a bunch of Python modules in a directory, all this is a derivation class. I need a “runner” script, which for each module creates an instance of the class that is inside it (the name of the actual class can be built by the name of the module file), and not a call to the “go” method for each of them.

I don’t know how many modules there are, but I can list all of them by dragging the directory through something like "bot _ *. Py"

I think this is something like "meta-programming", but how could there be a better (most elegant) way to do this?

+3
source share
4 answers
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])

__init__.py , "". "bot_" . windows linux.

+3

__import__() , dir(), , , , go():

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()
+4

, :

mainDir/
  runner.py
  package/
    __init__.py
    bot_moduleA.py
    bot_moduleB.py
    bot_moduleC.py

runner :


import types
import package

for moduleName in dir(package):
  module = package.__dict__[moduleName]
  if type(module) != types.ModuleType:
    continue

  for klassName in dir(module):
    klass = module.__dict__[klassName]
    if type(klass) != types.ClassType:
      continue
    klass().go()
+1

:

import glob
import os

filelist = glob.glob('bot_*.py')
for f in filelist:
    context = {}
    exec(open(f).read(), context)
    klassname = os.path.basename(f)[:-3] 
    klass = context[klassname]
    klass().go()

, , , , . , .

, glob , , os.path.basename(f) [: - 3], .

+1
source

Source: https://habr.com/ru/post/1702150/


All Articles