Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import logging
- import os
- import re
- _log = logging.getLogger(__name__)
- WRAPPER_TEMPLATE = """from PyQt5.QtWidgets import {base}
- from {ui_module} import Ui_{cls}
- class {cls}({base}):
- def __init__(self, parent=None):
- super({base}, self).__init__(parent)
- self.ui = Ui_{cls}()
- self.ui.setupUi(self)
- """
- CLASS_RE = re.compile('<class>([^<]+)')
- # У сгенерированного ui файла у <widget/> есть параметр name, его значение
- # совпадает с <class>CLASS_NAME</class>, но при генерации скрипта pyuic5.exe
- # использует содержимое <class/>
- BASE_RE = re.compile('<widget class="([^"]+)')
- def build_ui(src, dst, rel_import=False):
- cmd = "pyuic5 {} -o {}"
- if rel_import:
- cmd += " --from-imports"
- cmd = cmd.format(src, dst)
- _log.debug("cmd: %s", cmd)
- os.system(cmd)
- def build_rc(src, dst):
- cmd = "pyrcc5 {} -o {}".format(src, dst)
- _log.debug("cmd: %s", cmd)
- os.system(cmd)
- def build_wrapper(filename, ui_filename, ui_module):
- _log.debug("build wrapper %s", filename)
- with open(ui_filename, encoding="utf-8") as fp:
- content = fp.read()
- cls = CLASS_RE.search(content).group(1)
- base = BASE_RE.search(content).group(1)
- with open(filename, 'w', encoding='utf-8') as fp:
- fp.write(WRAPPER_TEMPLATE.format(
- cls=cls, base=base, ui_module=ui_module))
- def build_resources(path, rel_import=False):
- """Данная функция рекурсивно проходит по всем каталогам начиная с
- указанного и ищет файлы с расширениями .ui и .qrc, а затем компилирует их
- в python модули. Помимо этого создается обертка, использующая ui."""
- full_path = os.path.realpath(path)
- _log.debug("cmd: cd %s", full_path)
- os.chdir(full_path)
- for cur, dirs, files in os.walk(path):
- for filename in files:
- name, extension = os.path.splitext(filename)
- extension = extension.lower()
- if extension == '.ui':
- ui_module = "ui_" + name
- ui_module_path = os.path.join(cur, ui_module + '.py')
- if os.path.exists(ui_module_path):
- _log.info("file already exists: %s", ui_module_path)
- continue
- ui_path = os.path.join(cur, filename)
- build_ui(ui_path, ui_module_path, rel_import)
- wrapper_path = ui_path[:-3] + '.py'
- # Придется удалять ui_foo.py и foo.py
- if os.path.exists(wrapper_path):
- _log.info("file already exists: %s", wrapper_path)
- continue
- if rel_import:
- ui_module = '.' + ui_module
- build_wrapper(wrapper_path, ui_path, ui_module)
- elif extension == '.qrc':
- rc_path = os.path.join(cur, name + '_rc.py')
- if os.path.exists(rc_path):
- _log.info("file already exists: %s", rc_path)
- continue
- build_rc(os.path.join(cur, filename), rc_path)
- if __name__ == '__main__':
- import sys
- logging.basicConfig(level=logging.DEBUG)
- sys.exit(build_resources('.', True))
Advertisement
Add Comment
Please, Sign In to add comment