stuppid_bot

Untitled

Jan 24th, 2016
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.41 KB | None | 0 0
  1. import logging
  2. import os
  3. import re
  4.  
  5. _log = logging.getLogger(__name__)
  6.  
  7. WRAPPER_TEMPLATE = """from PyQt5.QtWidgets import {base}
  8. from {ui_module} import Ui_{cls}
  9.  
  10.  
  11. class {cls}({base}):
  12.    def __init__(self, parent=None):
  13.        super({base}, self).__init__(parent)
  14.        self.ui = Ui_{cls}()
  15.        self.ui.setupUi(self)
  16. """
  17. CLASS_RE = re.compile('<class>([^<]+)')
  18. # У сгенерированного ui файла у <widget/> есть параметр name, его значение
  19. # совпадает с <class>CLASS_NAME</class>, но при генерации скрипта pyuic5.exe
  20. # использует содержимое <class/>
  21. BASE_RE = re.compile('<widget class="([^"]+)')
  22.  
  23.  
  24. def build_ui(src, dst, rel_import=False):
  25.     cmd = "pyuic5 {} -o {}"
  26.     if rel_import:
  27.         cmd += " --from-imports"
  28.     cmd = cmd.format(src, dst)
  29.     _log.debug("cmd: %s", cmd)
  30.     os.system(cmd)
  31.  
  32.  
  33. def build_rc(src, dst):
  34.     cmd = "pyrcc5 {} -o {}".format(src, dst)
  35.     _log.debug("cmd: %s", cmd)
  36.     os.system(cmd)
  37.  
  38.  
  39. def build_wrapper(filename, ui_filename, ui_module):
  40.     _log.debug("build wrapper %s", filename)
  41.     with open(ui_filename, encoding="utf-8") as fp:
  42.         content = fp.read()
  43.     cls = CLASS_RE.search(content).group(1)
  44.     base = BASE_RE.search(content).group(1)
  45.     with open(filename, 'w', encoding='utf-8') as fp:
  46.         fp.write(WRAPPER_TEMPLATE.format(
  47.             cls=cls, base=base, ui_module=ui_module))
  48.  
  49.  
  50. def build_resources(path, rel_import=False):
  51.     """Данная функция рекурсивно проходит по всем каталогам начиная с
  52.    указанного и ищет файлы с расширениями .ui и .qrc, а затем компилирует их
  53.    в python модули. Помимо этого создается обертка, использующая ui."""
  54.     full_path = os.path.realpath(path)
  55.     _log.debug("cmd: cd %s", full_path)
  56.     os.chdir(full_path)
  57.     for cur, dirs, files in os.walk(path):
  58.         for filename in files:
  59.             name, extension = os.path.splitext(filename)
  60.             extension = extension.lower()
  61.             if extension == '.ui':
  62.                 ui_module = "ui_" + name
  63.                 ui_module_path = os.path.join(cur, ui_module + '.py')
  64.                 if os.path.exists(ui_module_path):
  65.                     _log.info("file already exists: %s", ui_module_path)
  66.                     continue
  67.                 ui_path = os.path.join(cur, filename)
  68.                 build_ui(ui_path, ui_module_path, rel_import)
  69.                 wrapper_path = ui_path[:-3] + '.py'
  70.                 # Придется удалять ui_foo.py и foo.py
  71.                 if os.path.exists(wrapper_path):
  72.                     _log.info("file already exists: %s", wrapper_path)
  73.                     continue
  74.                 if rel_import:
  75.                     ui_module = '.' + ui_module
  76.                 build_wrapper(wrapper_path, ui_path, ui_module)
  77.             elif extension == '.qrc':
  78.                 rc_path = os.path.join(cur, name + '_rc.py')
  79.                 if os.path.exists(rc_path):
  80.                     _log.info("file already exists: %s", rc_path)
  81.                     continue
  82.                 build_rc(os.path.join(cur, filename), rc_path)
  83.  
  84.  
  85. if __name__ == '__main__':
  86.     import sys
  87.  
  88.     logging.basicConfig(level=logging.DEBUG)
  89.     sys.exit(build_resources('.', True))
Advertisement
Add Comment
Please, Sign In to add comment