Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: UTF-8 -*-
- """ Module convertUiFiles: This looks through for .ui files and
- converts them to .py files in-place
- """
- import logging
- import sys
- import os
- from pysideuic import compileUi
- from cliUtils import ParseArgs
- # Grab command line arguments and setup logger
- parser = ParseArgs('Converts .ui files made with Qt Designer to python .py scripts.',
- 'mode',
- 'files',
- 'output')
- loggingLevel = parser.getLoggingLevel()
- logging.basicConfig(level=loggingLevel)
- logger = logging.getLogger(__name__)
- filesToConvert = parser.getFiles()
- overwriteExisting = parser.getOverwriteExisting()
- class ConvertUiFiles(object):
- """
- This class contains methods for converting Qt UI files to .py scripts.
- """
- # grab arguments passed from CLI
- def __init__(self,
- outputFile=None,
- overwriteExisting=overwriteExisting,
- backupExisting=False,
- files=filesToConvert):
- """
- The constructor.
- This also initiates the conversion of .ui to .py files.
- :param outputFile: ``str`` determining where to write the output file.
- :param overwriteExisting: ``bool`` determining if existing .py
- files should be overwritten in place.
- :param backupExisting: ``bool`` determining if existing .py files should be
- backed up before being overwritten.
- Has no effect if ``overwriteExisting`` is ``False``.
- :return: ``None``
- """
- if files:
- # If converting directory search for .ui files recursively
- if len(files) == 1 and os.path.isdir(files[0]):
- files = self.getUiFiles(files[0])
- for f in files:
- self.convertUiToPyFile(f, outputFile=outputFile,
- overwriteExisting=overwriteExisting,
- backupExisting=backupExisting)
- else:
- logger.error('### No files were specified for conversion!!!')
- @staticmethod
- def getUiFiles(basePath):
- """
- This method gets all available .ui files for conversion.
- :param basePath: ``str`` to path of root directory
- :return: ``list`` of files in base directory path
- :rtype: ``list``
- """
- filesFound = []
- for root, dirs, files in os.walk(basePath):
- for f in files:
- if f.endswith('.ui'):
- filesFound.append(os.path.join(root, f))
- return filesFound
- @staticmethod
- def convertUiToPyFile(sourceFile, outputFile=None,
- overwriteExisting=True, backupExisting=False ):
- """
- This method compiles the .ui files to .py files.
- :param sourceFile: ``str`` to path of source file
- :param outputFile: ``str`` to path of output file dest.
- :param overwriteExisting: ``bool`` determining if existing files
- should be overwritten with output file
- :param backupExisting: ``bool`` determining if existing file should
- be backed up before being overwritten
- :return: ``None``
- """
- logger.debug('Running file conversion for {0} to {1}...'
- .format(sourceFile, outputFile))
- if outputFile is None:
- outputFile = sourceFile.rsplit('.')[0]+'.py'
- # check if file already exists and backup file if necessary
- if os.path.isfile(outputFile):
- logger.warning('File:{0} already exists...'.format(outputFile))
- if overwriteExisting:
- logger.info('File: {0} will be overwritten...'.format(outputFile))
- if backupExisting:
- logger.debug('Backing up existing file before overwriting data...')
- os.rename(outputFile, outputFile+'.bkup')
- logger.debug('Renamed existing file to: {0}'.format(outputFile+'.bkup'))
- else:
- logger.warning('overwriteExisting not specified, skipping file: {0}'
- .format(outputFile))
- return None
- try: pyFile = open(outputFile, 'w')
- except IOError:
- logger.error('Unable to write to location: {0}\n{1}'
- .format(outputFile, sys.exc_info()[0]))
- raise IOError
- logger.info('Attempting to convert: {0} to: \n{1} ...'
- .format(sourceFile, outputFile))
- compileUi( sourceFile, pyFile )
- pyFile.close()
- logger.info('Conversion successful!\n')
- if __name__ == '__main__':
- # Run conversion
- conv = ConvertUiFiles()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement