Advertisement
Guest User

Untitled

a guest
Sep 27th, 2016
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.00 KB | None | 0 0
  1. from os import listdir
  2. from os.path import isfile, join
  3. import importlib
  4.  
  5. filepath = './'
  6. for f in listdir(filepath):
  7. if isfile(join(filepath, f)) and f != 'main.py':
  8. moduleloader = importlib.find_loader(f.split('.')[0])
  9. if moduleloader is not None:
  10. # check if module has function
  11.  
  12. import importlib
  13. from os import listdir
  14. from os.path import isfile, join, splitext
  15.  
  16. for f in listdir(filepath):
  17. if isfile(join(filepath, f)) and f != 'main.py':
  18. module_name, _ = splitext(f)
  19. m = importlib.import_module(module_name)
  20. if hasattr(m, 'function_name'):
  21. function_name = getattr(m, 'function_name')
  22. function_name()
  23.  
  24. import os, sys, itertools
  25.  
  26. def get_modules(fn_names: [str], folder: str) -> dict:
  27. sys.path.append(folder) # путь поиска модуля
  28. def get():
  29. for file in os.listdir(folder): # файлы+каталоги из folder
  30. if os.path.isfile(os.path.join(folder, file)): # только файлы
  31. name, ext = os.path.splitext(file)
  32. if ext == '.py': # расширения ".py"
  33. module = __import__(name) # локальный импорт модуля
  34. for fn in fn_names: # если несколько названий функций
  35. if hasattr(module, fn): # функция с определённым названием
  36. yield fn, module # вернуть модуль функции
  37. modules = {} # {функ1:[модуль1,..], функ2:[..],..}
  38. for f, m in get():
  39. try: modules[f].append(m)
  40. except KeyError: modules[f] = [m]
  41. return modules
  42.  
  43. if __name__ == '__main__':
  44. folder = '_Tmpc9'
  45.  
  46. def test_files_creator(dt: {int: [int]}):
  47. '''создать файлы модулей и записать функции'''
  48. md = 'module_{}.py'
  49. fn = '''def fn_{0}(arg): print("call %s( %s ) ~ %s" % (fn_{0}.__name__, arg, sys.modules[__name__]))'''
  50. if not os.path.isdir(folder): os.makedirs(folder)
  51. for m in dt:
  52. j = os.path.join(folder, md.format(m))
  53. print('import sysn', file=open(j, 'w'))
  54. for f in dt[m]: print(fn.format(f), file=open(j, 'a'))
  55.  
  56. test_files_creator({1: [1, 2], 2: [1, 2], 3: [2]})
  57.  
  58. ms = get_modules(fn_names=['fn_1', 'fn_2'], folder=folder)
  59.  
  60. print('n'.join('{}:{}<{} module'.format(k, [m.__name__ for m in v], len(v))
  61. for k, v in ms.items()))
  62. print()
  63.  
  64. m = ms['fn_1'][0]
  65. print(m)
  66. getattr(m, 'fn_1')('one')
  67.  
  68. # имя модуля и функции можно использовать как если бы был обычный import:
  69. # динамическое подключение модуля
  70. globals().update({m.__name__: m for m in set(itertools.chain(*ms.values()))})
  71. print(module_2)
  72. module_2.fn_1('two')
  73.  
  74. # динамическое подключение функции
  75. m = ms['fn_2'][2]
  76. globals()['fn_2'] = getattr(m, 'fn_2')
  77. print(m)
  78. fn_2('three')
  79.  
  80. fn_1:['module_1', 'module_2']<2 module
  81. fn_2:['module_1', 'module_2', 'module_3']<3 module
  82.  
  83. <module 'module_1' from '_Tmpc9\module_1.py'>
  84. call fn_1( one ) ~ <module 'module_1' from '_Tmpc9\module_1.py'>
  85. <module 'module_2' from '_Tmpc9\module_2.py'>
  86. call fn_1( two ) ~ <module 'module_2' from '_Tmpc9\module_2.py'>
  87. <module 'module_3' from '_Tmpc9\module_3.py'>
  88. call fn_2( three ) ~ <module 'module_3' from '_Tmpc9\module_3.py'>
  89.  
  90. #!/usr/bin/env python
  91. import inspect
  92. import pkgutil
  93.  
  94. for module_finder, name, ispkg in pkgutil.iter_modules(path=['modules']):
  95. if ispkg or name == __name__:
  96. continue # skip packages or itself
  97. mod = module_finder.find_module(name).load_module(name)
  98. g = next((f for funcname, f in inspect.getmembers(mod, inspect.isfunction)
  99. if funcname == 'g'), None) # find *g* function in the *mod* module
  100. if g is None:
  101. print('no g function in {} module'.format(name))
  102. else: # call it
  103. g()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement