Advertisement
ylSiew

fileUtils

Aug 10th, 2015
619
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.90 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: UTF-8 -*-
  3.  
  4. """ Module convertUiFiles: This looks through for .ui files and
  5. converts them to .py files in-place
  6. """
  7.  
  8. import logging
  9. import sys
  10.  
  11. import os
  12. from pysideuic import compileUi
  13. from cliUtils import ParseArgs
  14.  
  15. # Grab command line arguments and setup logger
  16. parser = ParseArgs('Converts .ui files made with Qt Designer to python .py scripts.',
  17.                    'mode',
  18.                    'files',
  19.                    'output')
  20.  
  21. loggingLevel = parser.getLoggingLevel()
  22. logging.basicConfig(level=loggingLevel)
  23. logger = logging.getLogger(__name__)
  24.  
  25. filesToConvert = parser.getFiles()
  26.  
  27. overwriteExisting = parser.getOverwriteExisting()
  28.  
  29.  
  30. class ConvertUiFiles(object):
  31.     """
  32.    This class contains methods for converting Qt UI files to .py scripts.
  33.    """
  34.  
  35.     # grab arguments passed from CLI
  36.  
  37.     def __init__(self,
  38.                  outputFile=None,
  39.                  overwriteExisting=overwriteExisting,
  40.                  backupExisting=False,
  41.                  files=filesToConvert):
  42.         """
  43.        The constructor.
  44.        This also initiates the conversion of .ui to .py files.
  45.  
  46.        :param outputFile: ``str`` determining where to write the output file.
  47.        :param overwriteExisting: ``bool`` determining if existing .py
  48.                        files should be overwritten in place.
  49.        :param backupExisting: ``bool`` determining if existing .py files should be
  50.                        backed up before being overwritten.
  51.                        Has no effect if ``overwriteExisting`` is ``False``.
  52.  
  53.        :return: ``None``
  54.        """
  55.  
  56.         if files:
  57.  
  58.             # If converting directory search for .ui files recursively
  59.             if len(files) == 1 and os.path.isdir(files[0]):
  60.                 files = self.getUiFiles(files[0])
  61.  
  62.             for f in files:
  63.                 self.convertUiToPyFile(f, outputFile=outputFile,
  64.                                        overwriteExisting=overwriteExisting,
  65.                                        backupExisting=backupExisting)
  66.  
  67.         else:
  68.             logger.error('### No files were specified for conversion!!!')
  69.  
  70.  
  71.     @staticmethod
  72.     def getUiFiles(basePath):
  73.         """
  74.        This method gets all available .ui files for conversion.
  75.  
  76.        :param basePath: ``str`` to path of root directory
  77.        :return: ``list`` of files in base directory path
  78.        :rtype: ``list``
  79.        """
  80.  
  81.         filesFound = []
  82.  
  83.         for root, dirs, files in os.walk(basePath):
  84.             for f in files:
  85.                 if f.endswith('.ui'):
  86.                    filesFound.append(os.path.join(root, f))
  87.  
  88.         return filesFound
  89.  
  90.  
  91.     @staticmethod
  92.     def convertUiToPyFile(sourceFile, outputFile=None,
  93.                           overwriteExisting=True, backupExisting=False ):
  94.         """
  95.        This method compiles the .ui files to .py files.
  96.  
  97.        :param sourceFile: ``str`` to path of source file
  98.        :param outputFile: ``str`` to path of output file dest.
  99.        :param overwriteExisting: ``bool`` determining if existing files
  100.                            should be overwritten with output file
  101.        :param backupExisting: ``bool`` determining if existing file should
  102.                                be backed up before being overwritten
  103.        :return: ``None``
  104.        """
  105.  
  106.         logger.debug('Running file conversion for {0} to {1}...'
  107.                      .format(sourceFile, outputFile))
  108.  
  109.         if outputFile is None:
  110.             outputFile = sourceFile.rsplit('.')[0]+'.py'
  111.  
  112.             # check if file already exists and backup file if necessary
  113.             if os.path.isfile(outputFile):
  114.                 logger.warning('File:{0} already exists...'.format(outputFile))
  115.  
  116.                 if overwriteExisting:
  117.                     logger.info('File: {0} will be overwritten...'.format(outputFile))
  118.  
  119.                     if backupExisting:
  120.                         logger.debug('Backing up existing file before overwriting data...')
  121.                         os.rename(outputFile, outputFile+'.bkup')
  122.                         logger.debug('Renamed existing file to: {0}'.format(outputFile+'.bkup'))
  123.  
  124.                 else:
  125.                     logger.warning('overwriteExisting not specified, skipping file: {0}'
  126.                                    .format(outputFile))
  127.                     return None
  128.  
  129.         try: pyFile = open(outputFile, 'w')
  130.         except IOError:
  131.             logger.error('Unable to write to location: {0}\n{1}'
  132.                          .format(outputFile, sys.exc_info()[0]))
  133.             raise IOError
  134.  
  135.         logger.info('Attempting to convert: {0} to: \n{1} ...'
  136.                      .format(sourceFile, outputFile))
  137.  
  138.         compileUi( sourceFile, pyFile )
  139.  
  140.         pyFile.close()
  141.  
  142.         logger.info('Conversion successful!\n')
  143.  
  144.  
  145. if __name__ == '__main__':
  146.  
  147.     # Run conversion
  148.     conv = ConvertUiFiles()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement