Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from os import listdir
- from os.path import isfile, join
- import importlib
- filepath = './'
- for f in listdir(filepath):
- if isfile(join(filepath, f)) and f != 'main.py':
- moduleloader = importlib.find_loader(f.split('.')[0])
- if moduleloader is not None:
- # check if module has function
- import importlib
- from os import listdir
- from os.path import isfile, join, splitext
- for f in listdir(filepath):
- if isfile(join(filepath, f)) and f != 'main.py':
- module_name, _ = splitext(f)
- m = importlib.import_module(module_name)
- if hasattr(m, 'function_name'):
- function_name = getattr(m, 'function_name')
- function_name()
- import os, sys, itertools
- def get_modules(fn_names: [str], folder: str) -> dict:
- sys.path.append(folder) # путь поиска модуля
- def get():
- for file in os.listdir(folder): # файлы+каталоги из folder
- if os.path.isfile(os.path.join(folder, file)): # только файлы
- name, ext = os.path.splitext(file)
- if ext == '.py': # расширения ".py"
- module = __import__(name) # локальный импорт модуля
- for fn in fn_names: # если несколько названий функций
- if hasattr(module, fn): # функция с определённым названием
- yield fn, module # вернуть модуль функции
- modules = {} # {функ1:[модуль1,..], функ2:[..],..}
- for f, m in get():
- try: modules[f].append(m)
- except KeyError: modules[f] = [m]
- return modules
- if __name__ == '__main__':
- folder = '_Tmpc9'
- def test_files_creator(dt: {int: [int]}):
- '''создать файлы модулей и записать функции'''
- md = 'module_{}.py'
- fn = '''def fn_{0}(arg): print("call %s( %s ) ~ %s" % (fn_{0}.__name__, arg, sys.modules[__name__]))'''
- if not os.path.isdir(folder): os.makedirs(folder)
- for m in dt:
- j = os.path.join(folder, md.format(m))
- print('import sysn', file=open(j, 'w'))
- for f in dt[m]: print(fn.format(f), file=open(j, 'a'))
- test_files_creator({1: [1, 2], 2: [1, 2], 3: [2]})
- ms = get_modules(fn_names=['fn_1', 'fn_2'], folder=folder)
- print('n'.join('{}:{}<{} module'.format(k, [m.__name__ for m in v], len(v))
- for k, v in ms.items()))
- print()
- m = ms['fn_1'][0]
- print(m)
- getattr(m, 'fn_1')('one')
- # имя модуля и функции можно использовать как если бы был обычный import:
- # динамическое подключение модуля
- globals().update({m.__name__: m for m in set(itertools.chain(*ms.values()))})
- print(module_2)
- module_2.fn_1('two')
- # динамическое подключение функции
- m = ms['fn_2'][2]
- globals()['fn_2'] = getattr(m, 'fn_2')
- print(m)
- fn_2('three')
- fn_1:['module_1', 'module_2']<2 module
- fn_2:['module_1', 'module_2', 'module_3']<3 module
- <module 'module_1' from '_Tmpc9\module_1.py'>
- call fn_1( one ) ~ <module 'module_1' from '_Tmpc9\module_1.py'>
- <module 'module_2' from '_Tmpc9\module_2.py'>
- call fn_1( two ) ~ <module 'module_2' from '_Tmpc9\module_2.py'>
- <module 'module_3' from '_Tmpc9\module_3.py'>
- call fn_2( three ) ~ <module 'module_3' from '_Tmpc9\module_3.py'>
- #!/usr/bin/env python
- import inspect
- import pkgutil
- for module_finder, name, ispkg in pkgutil.iter_modules(path=['modules']):
- if ispkg or name == __name__:
- continue # skip packages or itself
- mod = module_finder.find_module(name).load_module(name)
- g = next((f for funcname, f in inspect.getmembers(mod, inspect.isfunction)
- if funcname == 'g'), None) # find *g* function in the *mod* module
- if g is None:
- print('no g function in {} module'.format(name))
- else: # call it
- g()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement