예제 #1
0
파일: __main__.py 프로젝트: Tydus/vidcutter
 def parse_cmdline(self) -> None:
     self.parser = QCommandLineParser()
     self.parser.setApplicationDescription('\nVidCutter - the simplest + fastest video cutter & joiner')
     self.parser.addPositionalArgument('video', 'Preload video file', '[video]')
     self.parser.addPositionalArgument('project', 'Open VidCutter project file (.vcp)', '[project]')
     self.debug_option = QCommandLineOption(['debug'], 'debug mode; verbose console output & logging. ' +
                                            'This will basically output what is being logged to file to the ' +
                                            'console stdout. Mainly useful for debugging problems with your ' +
                                            'system video and/or audio stack and codec configuration.')
     self.dev_option = QCommandLineOption(['dev'], 'developer mode; disables the use of compiled resource files ' +
                                          'so that all app resources & assets are accessed directly from the file ' +
                                          'system allowing you to see UI changes immediately. this typically ' +
                                          'relates to changes made to Qt stylesheets (.qss), layout/templates, ' +
                                          'content includes and images. basically all assets defined in .qrc ' +
                                          'files throughout the codebase.')
     self.parser.addOption(self.debug_option)
     self.parser.addOption(self.dev_option)
     self.parser.addVersionOption()
     self.parser.addHelpOption()
     self.parser.process(qApp)
     self.args = self.parser.positionalArguments()
     if self.parser.isSet(self.debug_option):
         os.environ['DEBUG'] = '1'
     if self.parser.isSet(self.dev_option):
         self.devmode = True
     if len(self.args) > 0:
         file_path = QFileInfo(self.args[0]).absoluteFilePath()
         if not os.path.exists(file_path):
             sys.stderr.write('\nERROR: File not found: %s\n' % file_path)
             self.close()
             sys.exit(1)
         self.video = file_path
예제 #2
0
 def parse_cmdline(self) -> None:
     self.parser = QCommandLineParser()
     self.parser.setApplicationDescription(
         '\nVidCutter - the simplest + fastest media cutter & joiner')
     self.parser.addPositionalArgument('video', 'Preload video file',
                                       '[video]')
     self.parser.addPositionalArgument(
         'project', 'Open VidCutter project file (.vcp)', '[project]')
     self.debug_option = QCommandLineOption(
         ['debug'], 'debug mode; verbose console output & logging. '
         'This will basically output what is being logged to file to the '
         'console stdout. Mainly useful for debugging problems with your '
         'system video and/or audio stack and codec configuration.')
     self.parser.addOption(self.debug_option)
     self.parser.addVersionOption()
     self.parser.addHelpOption()
     self.parser.process(qApp)
     self.args = self.parser.positionalArguments()
     if self.parser.isSet(self.debug_option):
         os.environ['DEBUG'] = '1'
     if len(self.args) > 0:
         file_path = QFileInfo(self.args[0]).absoluteFilePath()
         if not os.path.exists(file_path):
             sys.stderr.write('\nERROR: File not found: %s\n' % file_path)
             self.close()
             qApp.exit(1)
         self.video = file_path
def runmain():
    import sys

    app = QApplication(sys.argv)

    cmdParser = QCommandLineParser()
    cmdParser.setApplicationDescription(
        'Room file merger utility script for Basement Renovator. Takes a config file and feeds it to the cli roommerger script'
    )
    cmdParser.addHelpOption()

    cmdParser.addPositionalArgument(
        'configFile',
        '''json config file to grab configuration from; sets current working directory to its directory. Format:
    {
        files: [
            {
                outputFile: path to file to output,
                paths: [ path to file/folder to replace, ... ],
                skipSTB: optional, true to skip generating the stb,
                noRecomputeIds: optional, true to skip recompute room ids,
                startingId: starting room id to recompute from
            }...
        ]
    }
    ''')

    fileEditedOpt = QCommandLineOption(
        'fileEdited',
        'optional file to limit which rooms get merged from the config',
        'file')
    cmdParser.addOption(fileEditedOpt)

    cmdParser.process(app)

    configArg = cmdParser.positionalArguments()[0]
    configPath = Path(configArg).absolute().resolve()
    if not configArg or not configPath.is_file():
        print('Invalid config path!')
        return

    fileEditedArg = cmdParser.value(fileEditedOpt)
    fileEditedPath = None
    if fileEditedArg:
        fileEditedPath = Path(fileEditedArg).absolute().resolve()
        if not fileEditedPath.is_file():
            print('Invalid edited file path!')
            return

    scriptPath = Path(__file__ + '/../roommerger.py').absolute().resolve()

    with open(configPath) as configFile:
        config = json.load(configFile)

        mergeRooms(config['files'],
                   str(scriptPath),
                   configPath.parent,
                   fileEdited=fileEditedPath)

    print('Success! Merged all.')
예제 #4
0
def process_args(app):
    args = {}

    parser = QCommandLineParser()
    parser.setApplicationDescription(
        ('PyMemorise is a tool to help memorise tables of data.' +
         ' It was built as an exam revision aid.'))
    parser.addHelpOption()
    parser.addVersionOption()

    dbOption = QCommandLineOption(
        ["database-file", "d"],
        "path to database, will be created if does not exist", "db",
        str(Path.home().joinpath(".pymem.db")))
    parser.addOption(dbOption)

    parser.process(app)

    args["database"] = parser.value(dbOption)

    if parser.positionalArguments():
        print(parser.positionalArguments())
        parser.showHelp()

    return args
예제 #5
0
파일: __main__.py 프로젝트: cas--/vidcutter
    def parse_cmdline(self) -> None:
        self.parser = QCommandLineParser()
        self.parser.setApplicationDescription(
            'The simply FAST & ACCURATE video cutter & joiner')
        self.parser.addPositionalArgument('video',
                                          'Preloads the video file in app.',
                                          '[video]')
        self.edl_option = QCommandLineOption(
            'edl', 'Preloads clip index from a previously saved EDL file.\n' +
            'NOTE: You must also set the video argument for this to work.',
            'edl file')
        self.debug_option = QCommandLineOption(
            ['d', 'debug'],
            'Output all info, warnings and errors to the console. ' +
            'This will basically output what is being logged to file to the ' +
            'console stdout. Mainly useful for debugging problems with your ' +
            'system video and/or audio stack and codec configuration.')

        self.parser.addOption(self.edl_option)
        self.parser.addOption(self.debug_option)
        self.parser.addVersionOption()
        self.parser.addHelpOption()
        self.parser.process(qApp)
        self.args = self.parser.positionalArguments()
        if self.parser.value('edl').strip() and not os.path.exists(
                self.parser.value('edl')):
            print('\n    ERROR: EDL file not found.\n', file=sys.stderr)
            self.close()
            sys.exit(1)
        if self.parser.value('edl').strip() and len(self.args) == 0:
            print('\n    ERROR: Video file argument is missing.\n',
                  file=sys.stderr)
            self.close()
            sys.exit(1)
        if self.parser.value('edl').strip():
            self.edl = self.parser.value('edl')
        if self.parser.isSet(self.debug_option):
            os.environ['DEBUG'] = '1'
        if len(self.args) > 0 and not os.path.exists(self.args[0]):
            print('\n    ERROR: Video file not found.\n', file=sys.stderr)
            self.close()
            sys.exit(1)
        if len(self.args) > 0:
            self.video = self.args[0]
예제 #6
0
def processArguments(arguments):
    parser = QCommandLineParser()
    parser.addHelpOption()
    parser.addVersionOption()

    delayOption = QCommandLineOption(["d", "delay"],
                                     "Take a screenshot after NUM seconds",
                                     "NUM")
    fullscreenOption = QCommandLineOption(
        ["f", "fullscreen"], "Take a screenshot of the whole screen")
    topWindowOption = QCommandLineOption(
        ["w", "top-window"], "Take a screenshot of the most top window")
    savePathOption = QCommandLineOption(
        ["s", "save-path"], "Specify a path to save the screenshot", "PATH")
    startFromDesktopOption = QCommandLineOption(
        ["i", "icon"],
        "Indicate that this program's started by clicking desktop file.")

    parser.addOption(delayOption)
    parser.addOption(fullscreenOption)
    parser.addOption(topWindowOption)
    parser.addOption(savePathOption)
    parser.addOption(startFromDesktopOption)
    parser.process(arguments)

    delay = int(parser.value(delayOption) or 0)
    fullscreen = bool(parser.isSet(fullscreenOption) or False)
    topWindow = bool(parser.isSet(topWindowOption) or False)
    savePath = str(parser.value(savePathOption) or "")
    startFromDesktop = bool(parser.isSet(startFromDesktopOption) or False)

    return {
        "delay": delay,
        "fullscreen": fullscreen,
        "topWindow": topWindow,
        "savePath": savePath,
        "startFromDesktop": startFromDesktop
    }
def directory(app):
    #app = QApplication(sys.argv)

    QCoreApplication.setApplicationVersion(QT_VERSION_STR)
    parser = QCommandLineParser()
    parser.setApplicationDescription("File Directory")
    parser.addHelpOption()
    parser.addVersionOption()

    dontUseCustomDirectoryIconsOption = QCommandLineOption(
        'C', "Set QFileIconProvider.DontUseCustomDirectoryIcons")
    parser.addOption(dontUseCustomDirectoryIconsOption)
    parser.addPositionalArgument('', "The directory to start in.")
    parser.process(app)
    try:
        rootPath = parser.positionalArguments().pop(0)
    except IndexError:
        rootPath = None

    model = QFileSystemModel()
    model.setRootPath('')
    filter = ['*.db']  #filtering out just by db
    model.setNameFilters(filter)
    model.setNameFilterDisables(0)  #Only show the filtered .db paths
    #filename = model.filePath()
    #print(filename)

    if parser.isSet(dontUseCustomDirectoryIconsOption):
        model.iconProvider().setOptions(
            QFileIconProvider.DontUseCustomDirectoryIcons)
    tree = QTreeView()
    tree.setModel(model)
    if rootPath is not None:
        rootIndex = model.index(QDir.cleanPath(rootPath))
        if rootIndex.isValid():
            tree.setRootIndex(rootIndex)

    # Demonstrating look and feel features.
    tree.setAnimated(False)
    tree.setIndentation(20)
    tree.setSortingEnabled(True)

    availableSize = QApplication.desktop().availableGeometry(tree).size()
    tree.resize(availableSize / 2)
    tree.setColumnWidth(0, tree.width() / 3)

    tree.setWindowTitle("Directory View")
    tree.show()

    sys.exit(app.exec_())
예제 #8
0
파일: box.py 프로젝트: cybrix-dev/fotobox
    def __init__(self, app):
        self.log = logs.logger.add_module("CliParser")
        QApplication.setApplicationName("fotobox")
        QApplication.setApplicationVersion("1.0")

        self.parser = QCommandLineParser()
        self.parser.setApplicationDescription("Fotobox")
        self.parser.addHelpOption()
        self.parser.addVersionOption()

        self.cursorOption = QCommandLineOption(["m", "mouse-cursor"],
                                               "Maus anzeigen")
        self.parser.addOption(self.cursorOption)

        self.configOption = QCommandLineOption(["c", "config"],
                                               "Systemkonfiguration setzen")
        self.parser.addOption(self.configOption)

        self.loggingOption = QCommandLineOption(["log"], "Logging aktivieren",
                                                "level", "INFO")
        self.parser.addOption(self.loggingOption)

        self.parser.process(app)
예제 #9
0
def main():
    app = QCoreApplication(sys.argv)

    # Set some application details.
    app.setApplicationName("MyApp")
    app.setApplicationVersion("0.1.0")
    app.setOrganizationName("My Organization")
    app.setOrganizationDomain("www.my-organization.org")

    # Create a verbosity command line option.
    verbose_option = QCommandLineOption(
        "verbose", "Verbose mode. Print out debug messages.")

    # Setup the commandline parser.
    command_parser = QCommandLineParser()
    command_parser.addHelpOption()
    command_parser.addVersionOption()

    # Add the commandline options.
    command_parser.addOption(verbose_option)

    # Process the command line.
    command_parser.process(app)

    # Set the basic logger mnessage format and verbosity level.
    logger = logging.getLogger()

    # This dictates how the messages are formatted.
    formatter = logging.Formatter(fmt=MESSAGE_FORMAT, style='{')

    # This handler sends everything to stdout.
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)

    # Add the handler to the logger.
    logger.addHandler(handler)

    # Check if the verbosity flag is set and set the log level to debug if it is.
    if command_parser.isSet(verbose_option):
        logger.setLevel(logging.DEBUG)
        logger.debug("Setting loglevel to debug.")

    else:
        logger.setLevel(logging.ERROR)

    # Start the event loop.
    sys.exit(app.exec())
예제 #10
0
def main(use_resources=False):

    parser = QCommandLineParser()
    geometryOpt = QCommandLineOption('geometry', 'Main window geometry',
                                     'geometry')
    parser.addOption(geometryOpt)
    parser.process(sys.argv)
    if parser.isSet('geometry'):
        try:
            geometry = tuple(
                int(val) for val in parser.value('geometry').split('x'))
            if len(geometry) != 4:
                raise
            if any(val < 1 for val in geometry):
                raise
        except:
            print(
                'The --geometry argument value must have a format such as 1x1x640x320 (x, y, width, height).'
            )
            exit(0)
    else:
        geometry = None

    app = QApplication(sys.argv)
    app.setApplicationName('pyrMExplorer')
    app.setOrganizationName('rMTools')
    if use_resources:
        icon_path = resource_path('icon.ico')
    else:
        icon_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                 'icon.ico')
    app.setWindowIcon(QIcon(icon_path))
    mainWindow = RmExplorerWindow()
    if geometry:
        mainWindow.setGeometry(*geometry)
    mainWindow.show()
    sys.exit(app.exec_())
예제 #11
0
if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)

    cmdParser = QCommandLineParser()
    cmdParser.setApplicationDescription(
        'Icon generator utility script for Basement Renovator. Takes an anm2 ')
    cmdParser.addHelpOption()

    cmdParser.addPositionalArgument('file',
                                    'anm2 file to generate the icon from')

    frameOpt = QCommandLineOption(['f', 'frame'],
                                  'frame in the anm2 to use, defaults to 0',
                                  'f', '0')
    cmdParser.addOption(frameOpt)

    animOpt = QCommandLineOption([
        'n', 'anim'
    ], 'name of the animation in the anm2 to use, defaults to the default anim',
                                 'n')
    cmdParser.addOption(animOpt)

    overlayOpt = QCommandLineOption(
        ['o', 'overlay-anim'],
        'name of an animation in the anm2 to use as an overlay (optional)',
        'o')
    cmdParser.addOption(overlayOpt)
예제 #12
0
    cmdParser.addPositionalArgument(
        'configFile', '''json config file to grab configuration from. Format:
    {
        files: [ absolute path to file to replace, ... ],
        entities: [
            {
                from: [ type, variant, subtype (can be -1 for wild card) ],
                to: [ type, variant, subtype (can be -1 for wild card) ],
            },
            ...
        ]
    }
    ''')

    stbOpt = QCommandLineOption(
        'stb', 'whether to save an stb version of the file next to it')
    cmdParser.addOption(stbOpt)

    cmdParser.process(app)

    args = cmdParser.positionalArguments()
    configArg = args[0]

    stbArg = cmdParser.isSet(stbOpt)

    with open(configArg) as configFile:
        config = json.load(configFile)

        totalRooms = 0
        print('Replacing entities:', config['entities'])
        for rf in config['files']:
예제 #13
0
def runmain():
    import sys

    app = QApplication(sys.argv)

    cmdParser = QCommandLineParser()
    cmdParser.setApplicationDescription(
        'Room file merger utility script for Basement Renovator. Takes a set of file paths'
    )
    cmdParser.addHelpOption()

    cmdParser.addPositionalArgument('file', 'xml files to merge')

    outputFileOpt = QCommandLineOption('output',
                                       'output filename, must be xml', 'file')
    cmdParser.addOption(outputFileOpt)

    stbOpt = QCommandLineOption(
        'stb', 'whether to save an stb version of the file next to it')
    cmdParser.addOption(stbOpt)

    noRecompIdsOpt = QCommandLineOption(
        'noRecomputeIds',
        'turn off recomputing room ids; useful for special room merging')
    cmdParser.addOption(noRecompIdsOpt)

    idOpt = QCommandLineOption(
        'startingId', 'optional starting id to use when recomputing room ids',
        'id')
    cmdParser.addOption(idOpt)

    skipOpt = QCommandLineOption(
        'roommerge',
        'placeholder argument used to prevent recursive execution')
    cmdParser.addOption(skipOpt)

    cmdParser.process(app)

    if cmdParser.isSet(skipOpt):
        print('Recursive execution from save hook, skipping')
        return

    paths = cmdParser.positionalArguments()
    if not paths:
        print('Must specify at least one file to merge!')
        return

    outputFileArg = cmdParser.value(outputFileOpt)
    outputFilePath = Path(outputFileArg).absolute().resolve()
    if not outputFileArg or outputFilePath.suffix != '.xml':
        print('Must specify xml output file!')
        return

    lastModified = None
    if outputFilePath.exists():
        lastModified = outputFilePath.stat().st_mtime

    idArg = cmdParser.value(idOpt)

    noRecompIdsArg = cmdParser.isSet(noRecompIdsOpt)
    stbArg = cmdParser.isSet(stbOpt)

    mergeRoomFile = None
    i = -1
    while (i + 1) < len(paths):
        i += 1

        file = paths[i]

        path = Path(file)
        if path.is_dir():
            files = list(filter(lambda f: f.suffix == '.xml', path.iterdir()))
            print('Adding xml files to queue from: ', path)
            del paths[i]
            i -= 1
            paths.extend(files)

    paths = list(filter(lambda f: Path(f).exists(), paths))

    if lastModified:
        anyModified = next(
            (file for file in paths if file.stat().st_mtime > lastModified),
            None) is not None
        if not anyModified:
            print('----')
            print(
                'Skipping since no xmls in folder have been modified since last update'
            )
            return

    for file in paths:
        print('----')
        print('Path:', file)

        path = Path(file)

        print('Merging file...')
        if path.suffix != '.xml':
            print('Must be xml! Skipping!')
            continue

        roomFile = cvt.xmlToCommon(path)
        if not mergeRoomFile:
            mergeRoomFile = roomFile
        else:
            mergeRoomFile.rooms.extend(roomFile.rooms)

    print('----')

    if not mergeRoomFile:
        print('No rooms files to merge')
        return

    if not noRecompIdsArg:
        recomputeRoomIDs(mergeRoomFile.rooms, idArg and int(idArg))

    cvt.commonToXML(outputFilePath, mergeRoomFile.rooms, file=mergeRoomFile)
    if stbArg:
        cvt.commonToSTBAB(outputFileArg.replace('.xml', '.stb'),
                          mergeRoomFile.rooms)

    settings = QSettings(__file__ + '/../../settings.ini', QSettings.IniFormat)
    saveHooks = settings.value('HooksSave')
    if saveHooks:
        fullPath = str(outputFilePath)
        for hook in saveHooks:
            hook = Path(hook).absolute().resolve()
            try:
                subprocess.run([str(hook), fullPath, '--save', '--roommerge'],
                               cwd=hook.parent,
                               timeout=60)
            except Exception as e:
                print('Save hook failed! Reason:', e)

    print('Success! Merged to', outputFileArg)
예제 #14
0
def main():
	multiprocessing.set_start_method('spawn')

	if markups.__version_tuple__ < (2, ):
		sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.')

	# If we're running on Windows without a console, then discard stdout
	# and save stderr to a file to facilitate debugging in case of crashes.
	if sys.executable.endswith('pythonw.exe'):
		sys.stdout = open(devnull, 'w')
		sys.stderr = open('stderr.log', 'w')

	try:
		# See https://github.com/retext-project/retext/issues/399
		# and https://launchpad.net/bugs/941826
		ctypes.CDLL('libGL.so.1', ctypes.RTLD_GLOBAL)
	except OSError:
		pass

	# Needed for Qt WebEngine on Windows
	QApplication.setAttribute(Qt.ApplicationAttribute.AA_ShareOpenGLContexts)
	QApplication.setAttribute(Qt.ApplicationAttribute.AA_UseHighDpiPixmaps)
	app = QApplication(sys.argv)
	app.setOrganizationName("ReText project")
	app.setApplicationName("ReText")
	app.setApplicationDisplayName("ReText")
	app.setApplicationVersion(app_version)
	app.setOrganizationDomain('mitya57.me')
	app.setDesktopFileName('me.mitya57.ReText.desktop')
	QNetworkProxyFactory.setUseSystemConfiguration(True)

	initializeDataDirs()
	RtTranslator = QTranslator()
	for path in datadirs:
		if RtTranslator.load('retext_' + globalSettings.uiLanguage,
		                     join(path, 'locale')):
			break
	QtTranslator = QTranslator()
	QtTranslator.load("qtbase_" + globalSettings.uiLanguage,
		QLibraryInfo.location(QLibraryInfo.LibraryLocation.TranslationsPath))
	app.installTranslator(RtTranslator)
	app.installTranslator(QtTranslator)

	parser = QCommandLineParser()
	parser.addHelpOption()
	parser.addVersionOption()
	previewOption = QCommandLineOption('preview',
		QApplication.translate('main', 'Open the files in preview mode'))
	newWindowOption = QCommandLineOption('new-window',
		QApplication.translate('main', 'Create a new window even if there is an existing one'))
	parser.addOption(previewOption)
	parser.addOption(newWindowOption)
	parser.addPositionalArgument('files',
		QApplication.translate('main', 'List of files to open'),
		'[files...]')

	parser.process(app)
	filesToOpen = parser.positionalArguments()

	print('Using configuration file:', settings.fileName())
	if globalSettings.appStyleSheet:
		sheetfile = QFile(globalSettings.appStyleSheet)
		sheetfile.open(QIODevice.OpenModeFlag.ReadOnly)
		app.setStyleSheet(QTextStream(sheetfile).readAll())
		sheetfile.close()
	window = ReTextWindow()

	openInExistingWindow = (globalSettings.openFilesInExistingWindow
		and not parser.isSet(newWindowOption))
	connection = QDBusConnection.sessionBus()
	if connection.isConnected() and openInExistingWindow:
		connection.registerObject('/', window, QDBusConnection.RegisterOption.ExportAllSlots)
		serviceName = 'me.mitya57.ReText'
		if not connection.registerService(serviceName) and filesToOpen:
			print('Opening the file(s) in the existing window of ReText.')
			iface = QDBusInterface(serviceName, '/', '', connection)
			for fileName in filesToOpen:
				iface.call('openFileWrapper', fileName)
			qWidgetIface = QDBusInterface(serviceName, '/', 'org.qtproject.Qt.QWidget', connection)
			qWidgetIface.call('raise')
			sys.exit(0)

	window.show()
	# ReText can change directory when loading files, so we
	# need to have a list of canonical names before loading
	fileNames = list(map(canonicalize, filesToOpen))
	readStdIn = False

	if globalSettings.openLastFilesOnStartup:
		window.restoreLastOpenedFiles()
	for fileName in fileNames:
		if QFile.exists(fileName):
			window.openFileWrapper(fileName)
			if parser.isSet(previewOption):
				window.actionPreview.setChecked(True)
				window.preview(True)
		elif fileName == '-':
			readStdIn = True

	inputData = ''
	if readStdIn and sys.stdin is not None:
		if sys.stdin.isatty():
			print('Reading stdin, press ^D to end...')
		inputData = sys.stdin.read()
	if inputData or not window.tabWidget.count():
		window.createNew(inputData)
	signal.signal(signal.SIGINT, lambda sig, frame: window.close())
	sys.exit(app.exec())
예제 #15
0
        """json config file to grab configuration from. Format:
    {
        files: [ absolute path to file to replace, ... ],
        entities: [
            {
                from: [ type, variant, subtype (can be -1 for wild card) ],
                to: [ type, variant, subtype (can be -1 for wild card) ],
            },
            ...
        ]
    }
    """,
    )

    stbOpt = QCommandLineOption(
        "stb", "whether to save an stb version of the file next to it"
    )
    cmdParser.addOption(stbOpt)

    cmdParser.process(app)

    args = cmdParser.positionalArguments()
    configArg = args[0]

    stbArg = cmdParser.isSet(stbOpt)

    with open(configArg) as configFile:
        config = json.load(configFile)

        totalRooms = 0
        print("Replacing entities:", config["entities"])
예제 #16
0
    - call parseConfigFile
    - show the QDialog
    - the application will process messages until it is told to exit
    """
    import sys, os
    from subprocess import Popen, PIPE
    from configparser import ConfigParser

    app = QApplication(sys.argv)
    app.setApplicationName("gitStatus.py")
    app.setApplicationVersion("1.0.0")

    clp = QCommandLineParser()  # handle command line options
    clp.addHelpOption()
    clp.addVersionOption()
    verboseOption = QCommandLineOption("verbose",
                                       "Issue progress messages to console.")
    clp.addOption(verboseOption)
    clp.process(sys.argv)

    GitStatus = QtWidgets.QDialog()  # create QDialog
    ui = Ui_GitStatus()  # instantiate ui
    ui.setupUi(GitStatus)  # configure all widgets
    ui.isVerbose = clp.isSet(verboseOption)

    if not ui.parseConfigFile():  # read the .ini file
        sys.exit(1)

    ui.populateDialog()  # populate the dialog's widgets

    GitStatus.show()  # make the dialog visible
    sys.exit(app.exec_())  # handle all messages until exit
예제 #17
0
 def __init__(self, args):
     super().__init__()
     self.args = args
     settings = QSettings()
     self.imageParam = {
         Option.DPI: settings.value("Export/exportDPI", 150, type=int),
         Option.QUAL: settings.value("Export/exportQuality", 80, type=int),
     }
     self.cli_mode = False
     self.requestedRecursive = False
     self.overwrite = Overwrite.UNSET
     self.dstDir = ""
     self._initStrings()
     self.parser = QCommandLineParser()
     #self.parser.setSingleDashWordOptionMode(QCommandLineself.parser.ParseAsLongOptions)
     self.parser.setApplicationDescription(
         self._appDescriptionStr.format(productName=__productname__))
     # Adding the '-h, --help' option
     self.parser.addHelpOption()
     # Adding the '-v --version' option
     self.parser.addVersionOption()
     # Allowing positional arguments (the file/files to open or process)
     self.parser.addPositionalArgument(
         _translate(
             "CommandLine", "path",
             "Commandline argument name. If you translate this name, translate it accordingly into the path description and path syntax."
         ), self._pathDescriptionStr,
         _translate(
             "CommandLine", "[<path> [ <path2>...]]",
             "Commandline argument syntax. If you translate <path>, translate the name and path description accordingly."
         ))
     # Adding command line options
     self.options = {
         Option.TIKZ:
         QCommandLineOption(
             ["t", "tikz"],
             self._batchOptionStr.format(formatID='TIkZ'),
         ),
         Option.PDF:
         QCommandLineOption(
             ["f", "pdf"],
             self._batchOptionStr.format(formatID='PDF'),
         ),
         Option.PNG:
         QCommandLineOption(
             ["p", "png"],
             self._batchOptionStr.format(formatID='PNG'),
         ),
         Option.JPEG:
         QCommandLineOption(
             ["j", "jpeg"],
             self._batchOptionStr.format(formatID='JPEG'),
         ),
         Option.SVG:
         QCommandLineOption(
             ["s", "svg"],
             self._batchOptionStr.format(formatID='SVG'),
         ),
         Option.DPI:
         QCommandLineOption(
             ["dpi"],
             self._dpiOptionStr.format(
                 defaultDPI=self.imageParam[Option.DPI]),
             "N",
         ),
         Option.QUAL:
         QCommandLineOption(
             ["quality"],
             self._qualityOptionStr.format(
                 defaultQuality=self.imageParam[Option.QUAL]),
             "Q",
         ),
         Option.DEST:
         QCommandLineOption(
             ["destination"],
             self._destDirOptionStr,
             "D",
         ),
         Option.LINK:
         QCommandLineOption(
             ["links"],
             self._followLinksOptionStr,
         ),
         Option.OVER:
         QCommandLineOption(
             ["overwrite"],
             self._overwriteOptionStr,
         ),
         Option.REC:
         QCommandLineOption(
             ["r"],
             self._recurseOptionStr,
         ),
     }
     # Adding the options in the list
     for option in self.options.values():
         self.parser.addOption(option)
예제 #18
0
    QCommandLineParser,
    QCoreApplication,
    QDir,
    QT_VERSION_STR,
)
from PyQt5.QtWidgets import QApplication, QFileIconProvider, QFileSystemModel, QTreeView

app = QApplication(sys.argv)

QCoreApplication.setApplicationVersion(QT_VERSION_STR)
parser = QCommandLineParser()
parser.setApplicationDescription("Qt Dir View Example")
parser.addHelpOption()
parser.addVersionOption()

dontUseCustomDirectoryIconsOption = QCommandLineOption(
    "c", "Set QFileIconProvider.DontUseCustomDirectoryIcons")
parser.addOption(dontUseCustomDirectoryIconsOption)
parser.addPositionalArgument("directory", "The directory to start in.")
parser.process(app)
try:
    rootPath = parser.positionalArguments().pop(0)
except IndexError:
    rootPath = None

model = QFileSystemModel()
model.setRootPath("")
if parser.isSet(dontUseCustomDirectoryIconsOption):
    model.iconProvider().setOptions(
        QFileIconProvider.DontUseCustomDirectoryIcons)
tree = QTreeView()
tree.setModel(model)
예제 #19
0
if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)

    cmdParser = QCommandLineParser()
    cmdParser.setApplicationDescription(
        "Icon generator utility script for Basement Renovator. Takes an anm2 "
    )
    cmdParser.addHelpOption()

    cmdParser.addPositionalArgument("file", "anm2 file to generate the icon from")

    frameOpt = QCommandLineOption(
        ["f", "frame"], "frame in the anm2 to use, defaults to 0", "f", "0"
    )
    cmdParser.addOption(frameOpt)

    animOpt = QCommandLineOption(
        ["n", "anim"],
        "name of the animation in the anm2 to use, defaults to the default anim",
        "n",
    )
    cmdParser.addOption(animOpt)

    overlayOpt = QCommandLineOption(
        ["o", "overlay-anim"],
        "name of an animation in the anm2 to use as an overlay (optional)",
        "o",
    )