コード例 #1
0
ファイル: Pip.py プロジェクト: metamarcdw/.dotfiles
    def runProcess(self, args, cmd=""):
        """
        Public method to execute the current pip with the given arguments.
        
        The selected pip executable is called with the given arguments and
        waited for its end.
        
        @param args list of command line arguments (list of string)
        @param cmd pip command to be used (string)
        @return tuple containing a flag indicating success and the output
            of the process (string)
        """
        if not cmd:
            cmd = self.__plugin.getPreferences("CurrentPipExecutable")
        ioEncoding = Preferences.getSystem("IOEncoding")

        process = QProcess()
        process.start(cmd, args)
        procStarted = process.waitForStarted()
        if procStarted:
            finished = process.waitForFinished(30000)
            if finished:
                if process.exitCode() == 0:
                    output = str(process.readAllStandardOutput(), ioEncoding,
                                 'replace')
                    return True, output
                else:
                    return False, self.tr("pip exited with an error ({0}).")\
                        .format(process.exitCode())
            else:
                process.terminate()
                process.waitForFinished(2000)
                process.kill()
                process.waitForFinished(3000)
                return False, self.tr("pip did not finish within 30 seconds.")

        return False, self.tr("pip could not be started.")
コード例 #2
0
    def programBootloader(self):
        goodPort, portErr = self.checkPort()
        if not goodPort:
            self.bootloaderFailed.emit(
                "Couldn't open serial port: {}".format(portErr))
            return

        self.isProgramming = True
        self.lpc21ispOutput = ''
        self.bootloaderPercent = 0
        self.bootloaderState = ''
        self.bootloaderStatus.emit(0, '')

        # lpc21isp process
        self.bootloaderProcess = QProcess()
        self.bootloaderProcess.errorOccurred.connect(
            self.processBootloaderError)
        self.bootloaderProcess.readyReadStandardOutput.connect(
            self.onBootloaderDataReady)
        self.bootloaderProcess.readyReadStandardError.connect(
            self.onBootloaderErrorReady)
        self.bootloaderProcess.finished.connect(self.onLPC21ISPFinished)
        self.stopSignal.connect(self.bootloaderProcess.kill)

        program = resource.path('exes/lpc21isp')
        if sys.platform.startswith('win'):
            program += '.exe'
        args = [
            "-wipe",
            resource.path("firmwares/ota-bootloader.hex"),
            self.portName,
            "38400",  # baudrate
            "12000"  # crystal frequency on board
        ]
        if sys.platform.startswith('win'):
            args[2] = "\\\\.\\" + self.portName
        self.bootloaderProcess.start(program, args)
コード例 #3
0
    def getGuardsList(self, repodir, all=True):
        """
        Public method to get a list of all guards defined.
        
        @param repodir directory name of the repository (string)
        @param all flag indicating to get all guards (boolean)
        @return sorted list of guards (list of strings)
        """
        guardsList = []

        args = self.vcs.initCommand("qselect")
        if all:
            args.append("--series")

        client = self.vcs.getClient()
        output = ""
        if client:
            output = client.runcommand(args)[0]
        else:
            process = QProcess()
            process.setWorkingDirectory(repodir)
            process.start('hg', args)
            procStarted = process.waitForStarted(5000)
            if procStarted:
                finished = process.waitForFinished(30000)
                if finished and process.exitCode() == 0:
                    output = str(process.readAllStandardOutput(),
                                 self.vcs.getEncoding(), 'replace')

        for guard in output.splitlines():
            guard = guard.strip()
            if all:
                guard = guard[1:]
            if guard not in guardsList:
                guardsList.append(guard)

        return sorted(guardsList)
コード例 #4
0
    def start(self, arguments):
        """
        Public slot to start the virtualenv command.
        
        @param arguments commandline arguments for virtualenv/pyvenv program
            (list of strings)
        """
        if self.__callIndex == 0:
            # first attempt, add a given python interpreter and do
            # some other setup
            self.errorGroup.hide()
            self.contents.clear()
            self.errors.clear()

            self.process = QProcess()
            self.process.readyReadStandardOutput.connect(self.__readStdout)
            self.process.readyReadStandardError.connect(self.__readStderr)
            self.process.finished.connect(self.__finish)

            if not self.__pyvenv:
                for arg in arguments:
                    if arg.startswith("--python="):
                        prog = arg.replace("--python=", "")
                        self.__calls.insert(0, (prog, ["-m", "virtualenv"]))
                        break
            self.__callArgs = arguments

        prog, args = self.__calls[self.__callIndex]
        args.extend(self.__callArgs)
        self.__cmd = "{0} {1}".format(prog, " ".join(args))
        self.__logOutput(self.tr("Executing: {0}\n").format(self.__cmd))
        self.process.start(prog, args)
        procStarted = self.process.waitForStarted(5000)
        if not procStarted:
            self.__logOutput(self.tr("Failed\n\n"))
            self.__nextAttempt()
コード例 #5
0
    def __init__(self, parent: QWidget = None) -> None:
        super().__init__(parent)

        self._vbox = QVBoxLayout(self)

        self._output = QTextEdit()
        self._output.setReadOnly(True)
        self._vbox.addWidget(self._output)

        self._progress = ProgressBar()
        self._progress.show_empty()
        self._vbox.addWidget(self._progress)

        self._cancel_button = QPushButton("Zurück")
        self._cancel_button.clicked.connect(self.on_cancel_clicked)
        self._vbox.addWidget(self._cancel_button)

        self._process = QProcess()
        self._process.setProcessChannelMode(QProcess.MergedChannels)
        self._process.readyRead.connect(self.on_process_ready_read)
        self._process.started.connect(self.on_process_started)
        self._process.finished.connect(self.on_process_finished)

        self.status_message.connect(self.on_status_message)
コード例 #6
0
    def on_file_open(self, submission_db_object):
        """
        Open the already downloaded file associated with the message (which
        is a Submission).
        """

        # Once downloaded, submissions are stored in the data directory
        # with the same filename as the server, except with the .gz.gpg
        # stripped off.
        server_filename = submission_db_object.filename
        fn_no_ext, _ = os.path.splitext(os.path.splitext(server_filename)[0])
        submission_filepath = os.path.join(self.data_dir, fn_no_ext)

        if self.proxy:
            # Running on Qubes.
            command = "qvm-open-in-vm"
            args = ['$dispvm:sd-svs-disp', submission_filepath]
            # QProcess (Qt) or Python's subprocess? Who cares? They do the
            # same thing. :-)
            process = QProcess(self)
            process.start(command, args)
        else:  # pragma: no cover
            # Non Qubes OS. Just log the event for now.
            logger.info('Opening file "{}".'.format(submission_filepath))
コード例 #7
0
    def __init__(self, vcs, parent=None):
        """
        Constructor
        
        @param vcs reference to the vcs object
        @param parent parent widget (QWidget)
        """
        super(HgConflictsListDialog, self).__init__(parent)
        self.setupUi(self)

        self.__position = QPoint()

        self.buttonBox.button(QDialogButtonBox.Close).setEnabled(False)
        self.buttonBox.button(QDialogButtonBox.Cancel).setDefault(True)

        self.conflictsList.headerItem().setText(
            self.conflictsList.columnCount(), "")
        self.conflictsList.header().setSortIndicator(0, Qt.AscendingOrder)

        self.refreshButton = self.buttonBox.addButton(
            self.tr("&Refresh"), QDialogButtonBox.ActionRole)
        self.refreshButton.setToolTip(
            self.tr("Press to refresh the list of conflicts"))
        self.refreshButton.setEnabled(False)

        self.vcs = vcs
        self.project = e5App().getObject("Project")

        self.__hgClient = vcs.getClient()
        if self.__hgClient:
            self.process = None
        else:
            self.process = QProcess()
            self.process.finished.connect(self.__procFinished)
            self.process.readyReadStandardOutput.connect(self.__readStdout)
            self.process.readyReadStandardError.connect(self.__readStderr)
コード例 #8
0
    def __init__(self, vcs, parent=None):
        """
        Constructor
        
        @param vcs reference to the vcs object
        @param parent parent widget (QWidget)
        """
        super(HgSummaryDialog, self).__init__(parent)
        self.setupUi(self)

        self.refreshButton = self.buttonBox.addButton(
            self.tr("Refresh"), QDialogButtonBox.ActionRole)
        self.refreshButton.setToolTip(
            self.tr("Press to refresh the summary display"))
        self.refreshButton.setEnabled(False)

        self.vcs = vcs
        self.vcs.committed.connect(self.__committed)

        self.process = QProcess()
        prepareProcess(self.process, language="C")
        self.process.finished.connect(self.__procFinished)
        self.process.readyReadStandardOutput.connect(self.__readStdout)
        self.process.readyReadStandardError.connect(self.__readStderr)
コード例 #9
0
    def __init__(self, vcs, parent=None):
        """
        Constructor
        
        @param vcs reference to the vcs object
        @param parent reference to the parent widget (QWidget)
        """
        super(HgGpgSignaturesDialog, self).__init__(parent)
        self.setupUi(self)
        self.setWindowFlags(Qt.Window)

        self.buttonBox.button(QDialogButtonBox.Close).setEnabled(False)
        self.buttonBox.button(QDialogButtonBox.Cancel).setDefault(True)

        self.process = QProcess()
        self.vcs = vcs
        self.__hgClient = vcs.getClient()

        self.process.finished.connect(self.__procFinished)
        self.process.readyReadStandardOutput.connect(self.__readStdout)
        self.process.readyReadStandardError.connect(self.__readStderr)

        self.show()
        QCoreApplication.processEvents()
コード例 #10
0
ファイル: file_copier.py プロジェクト: BrunoVernay/RaySession
    def __init__(self, session):
        ServerSender.__init__(self)
        self.session = session
        self.client_id = ''
        self.next_function = None
        self.abort_function = None
        self.next_args = []
        self.copy_files = []
        self.copy_size = 0
        self.aborted = False
        self.is_active = False

        self.process = QProcess()
        self.process.finished.connect(self.processFinished)
        if ray.QT_VERSION >= (5, 6):
            self.process.errorOccurred.connect(self.errorOccurred)

        self.timer = QTimer()
        self.timer.setInterval(250)
        self.timer.setSingleShot(True)
        self.timer.timeout.connect(self.checkProgressSize)

        self._abort_src_addr = None
        self._abort_src_path = ''
コード例 #11
0
def run_qprocess(cmd: str, *args: str, cwd=None) -> str:
    """Run a shell command synchronously using QProcess.

    Args:
        cmd: The command to run.
        args: Any arguments passed to the command.
        cwd: Directory of the command to run in.
    Returns:
        The starndard output of the command.
    Raises:
        OSError on failure.
    """
    process = QProcess()
    if cwd is not None:
        process.setWorkingDirectory(cwd)
    process.start(cmd, args)
    if not process.waitForFinished():
        raise OSError("Error waiting for process")
    if process.exitStatus() != QProcess.NormalExit:
        stderr = str(process.readAllStandardError(),
                     "utf-8").strip()  # type: ignore
        raise OSError(stderr)
    return str(process.readAllStandardOutput(),
               "utf-8").strip()  # type: ignore
コード例 #12
0
    def __init__(self, vcs, parent=None):
        """
        Constructor
        
        @param vcs reference to the vcs object
        @param parent parent widget (QWidget)
        """
        super(HgQueuesListDialog, self).__init__(parent)
        self.setupUi(self)
        self.setWindowFlags(Qt.Window)

        self.buttonBox.button(QDialogButtonBox.Close).setEnabled(False)
        self.buttonBox.button(QDialogButtonBox.Cancel).setDefault(True)

        self.vcs = vcs
        self.__hgClient = vcs.getClient()

        self.patchesList.header().setSortIndicator(0, Qt.AscendingOrder)

        if self.__hgClient:
            self.process = None
        else:
            self.process = QProcess()
            self.process.finished.connect(self.__procFinished)
            self.process.readyReadStandardOutput.connect(self.__readStdout)
            self.process.readyReadStandardError.connect(self.__readStderr)

        self.__statusDict = {
            "A": self.tr("applied"),
            "U": self.tr("not applied"),
            "G": self.tr("guarded"),
            "D": self.tr("missing"),
        }

        self.show()
        QCoreApplication.processEvents()
コード例 #13
0
    def start_tribler_core(self):
        self.use_existing_core = False

        core_env = self.core_env
        if not core_env:
            core_env = QProcessEnvironment.systemEnvironment()
            core_env.insert("CORE_API_PORT", f"{self.api_port}")
            core_env.insert("CORE_API_KEY", self.api_key)
            core_env.insert("TSTATEDIR", str(self.root_state_dir))

        core_args = self.core_args
        if not core_args:
            core_args = sys.argv + ['--core']

        self.core_process = QProcess()
        self.core_process.setProcessEnvironment(core_env)
        self.core_process.setProcessChannelMode(QProcess.SeparateChannels)
        connect(self.core_process.started, self.on_core_started)
        connect(self.core_process.readyReadStandardOutput,
                self.on_core_stdout_read_ready)
        connect(self.core_process.readyReadStandardError,
                self.on_core_stderr_read_ready)
        connect(self.core_process.finished, self.on_core_finished)
        self.core_process.start(sys.executable, core_args)
コード例 #14
0
ファイル: Terminal.py プロジェクト: simongarisch/PyPad
    def __init__(self, parent=None):
        super().__init__()
        self.parent = parent
        self.pressed = False
        self.font = QFont()
        self.dialog = MessageBox(self)
        self.font.setFamily(editor["editorFont"])
        self.font.setPointSize(12)
        self.layout = QVBoxLayout()

        self.setLayout(self.layout)
        self.output = None
        self.setFocusPolicy(Qt.StrongFocus)
        self.error = None
        self.finished = False
        self.clicked = False

        self.process = QProcess()
        self.state = None
        self.process.readyReadStandardError.connect(
            self.onReadyReadStandardError)
        self.process.readyReadStandardOutput.connect(
            self.onReadyReadStandardOutput)
        self.add()  # Add items to the layout
コード例 #15
0
ファイル: widgets.py プロジェクト: huazhicai/crawler
    def runGraph(self):
        controller = ControllerManager().getController(self.controllerKey)
        data = controller.getData()

        config_data = single_file_export(data)
        # self.thread = CrawlThread(config_data)  # 创建线程
        # self.thread.started.connect(lambda: print('=========== Starting Crawl =========='))
        # self.thread.start()
        # self.thread.finished.connect(lambda: print("============ Done ================"))

        # 开启爬虫子

        from crawler_graph.crawler import crawl
        import multiprocessing
        try:
            process = multiprocessing.Process(target=crawl,
                                              args=(config_data, ))
            process.start()
        except Exception as e:
            print(f'Crawler Error: {e}')

        # 开启爬虫子进程
        obj_file = os.path.join(os.path.dirname(os.path.dirname(__file__)),
                                'crawler_graph', 'TestOne.py')
        # obj_file = resource_path(obj_file)

        self.process = QProcess(self)
        self.process.readyReadStandardOutput.connect(self.stdoutReady)
        self.process.readyReadStandardError.connect(self.stderrReady)
        # start_time = datetime.now()
        self.process.started.connect(
            lambda: print('********* Started! **********'))
        self.process.finished.connect(
            lambda: print('********** Finished! *** Timer: {} *********'.
                          format(datetime.now() - start_time)))
        self.process.start('python', [obj_file, str(config_data)])
コード例 #16
0
    def __startExternalClient(self, interpreter, port):
        """
        Private method to start the background client as external process.
        
        @param interpreter path and name of the executable to start (string)
        @param port socket port to which the interpreter should connect (int)
        @return the process object (QProcess or None)
        """
        if interpreter == "" or not Utilities.isinpath(interpreter):
            return None

        backgroundClient = os.path.join(getConfig('ericDir'), "Utilities",
                                        "BackgroundClient.py")
        proc = QProcess()
        proc.setProcessChannelMode(QProcess.ForwardedChannels)
        args = [
            backgroundClient, self.hostAddress,
            str(port),
            str(Preferences.getUI("BackgroundServiceProcesses"))
        ]
        proc.start(interpreter, args)
        if not proc.waitForStarted(10000):
            proc = None
        return proc
コード例 #17
0
 def __startProcess(self, program, arguments, environment=None):
     """
     Private method to start the debugger client process.
     
     @param program name of the executable to start (string)
     @param arguments arguments to be passed to the program (list of string)
     @param environment dictionary of environment settings to pass
         (dict of string)
     @return the process object (QProcess) or None
     """
     proc = QProcess()
     if environment is not None:
         env = QProcessEnvironment()
         for key, value in list(environment.items()):
             env.insert(key, value)
         proc.setProcessEnvironment(env)
     args = []
     for arg in arguments:
         args.append(arg)
     proc.start(program, args)
     if not proc.waitForStarted(10000):
         proc = None
     
     return proc
コード例 #18
0
 def __init__(self, library_path):
     """Class initializer."""
     self._library_path = library_path
     self._process = QProcess()
コード例 #19
0
    def __init__(self):
        super(Window, self).__init__()

        self.path = ""
        self.save_path = ""
        self.timer = QTimer(self)

        self.box_h_tips = QHBoxLayout()
        self.l_tips = QLabel()

        self.l_tips.setStyleSheet("color:red")
        self.l_tips.setLayout(self.box_h_tips)

        # ======== tap 1 ==============================
        self.l_img_path = QLabel("图片路径:")
        self.e_img_path = QLineEdit()
        self.e_img_path.setReadOnly(True)
        self.b_open_to_select_img_path = QPushButton("...")
        self.b_open_to_select_img_path.setToolTip("选择文件")

        def open_to_select_img_path():
            pre_path = self.path
            self.path = QFileDialog.getOpenFileName(self, "选择文件...",
                                                    self.path)[0]
            if self.path == "":
                self.path = pre_path
                return
            self.e_img_path.setText(self.path)
            self.img_to_b64str()
            self.b64str_to_img()

        self.b_open_to_select_img_path.clicked.connect(open_to_select_img_path)

        # ================= convert ========================
        self.b_img_to_b64str = QPushButton("图片转base64")

        self.b_img_to_b64str.clicked.connect(self.img_to_b64str)

        self.e_img_result = QTextEdit()
        self.e_img_result.setAcceptRichText(False)

        def text_change():
            self.e_img_result.moveCursor(QTextCursor.End)
            self.b64str_to_img()

        self.e_img_result.textChanged.connect(text_change)

        self.b_b64str_to_img = QPushButton("base64转图片")

        self.b_b64str_to_img.clicked.connect(self.b64str_to_img)

        self.b_save = QPushButton("保存原图")

        def save():
            try:
                self.save_path = QFileDialog.getSaveFileName(
                    self, "保存图片", self.save_path)[0]
                if self.save_path == "":
                    self.alert("取消保存")
                    return
                img = base64_to_pixmap(self.e_img_result.toPlainText())
                if img.save(self.save_path):
                    self.alert("保存成功,路径:" + self.save_path)
                else:
                    self.alert("保存失败!")
            except Exception as e:
                self.alert(str(e))

        self.b_save.clicked.connect(save)

        self.b_clear = QPushButton("清空")
        self.b_clear.clicked.connect(self.e_img_result.clear)

        self.box_v_img_to_b64str = QVBoxLayout()
        self.l_img = QLabel()
        self.box_v_img_to_b64str.addWidget(self.l_img)
        self.l_img.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter)

        self.g_b64str_to_img = QGroupBox("转换缩略图")
        self.g_b64str_to_img.setLayout(self.box_v_img_to_b64str)

        self.box_g_img_to_b64str = QGridLayout()
        self.box_g_img_to_b64str.addWidget(self.l_img_path, 0, 0)
        self.box_g_img_to_b64str.addWidget(self.e_img_path, 0, 1)
        self.box_g_img_to_b64str.addWidget(self.b_open_to_select_img_path, 0,
                                           2)
        self.box_g_img_to_b64str.addWidget(self.b_img_to_b64str, 0, 3)
        self.box_g_img_to_b64str.addWidget(self.b_b64str_to_img, 0, 4)
        self.box_g_img_to_b64str.addWidget(self.b_save, 0, 5)
        self.box_g_img_to_b64str.addWidget(self.b_clear, 0, 6)
        self.box_g_img_to_b64str.addWidget(self.e_img_result, 1, 0, 1, 3)
        self.box_g_img_to_b64str.addWidget(self.g_b64str_to_img, 1, 3, 1, 4)

        self.g_img_to_b64str = QGroupBox("图片与base64互转")
        self.g_img_to_b64str.setLayout(self.box_g_img_to_b64str)
        # ======== tap 1 ==============================
        # ======== tap 2 ==============================

        self.e_url_string = QTextEdit()
        self.e_url_string.setAcceptRichText(False)
        self.e_url_string_result = QTextEdit()
        self.e_url_string_result.setReadOnly(True)
        self.b_url_string_encode = QPushButton("url编码")

        def url_string_encode():
            try:
                self.e_url_string_result.clear()
                self.e_url_string_result.setText(
                    quote_plus(self.e_url_string.toPlainText()))
            except Exception as e:
                self.alert(str(e))

        self.b_url_string_encode.clicked.connect(url_string_encode)
        self.b_url_string_decode = QPushButton("url解码")

        def url_string_decode():
            try:
                self.e_url_string_result.clear()
                self.e_url_string_result.setText(
                    unquote_plus(self.e_url_string.toPlainText()))
            except Exception as e:
                self.alert(str(e))

        self.b_url_string_decode.clicked.connect(url_string_decode)

        self.b_url_string_paste_decode = QPushButton("粘贴并解码")

        def url_string_paste_decode():
            self.e_url_string.setText(QApplication.clipboard().text())
            url_string_decode()

        self.b_url_string_paste_decode.clicked.connect(url_string_paste_decode)
        self.b_url_string_paste_encode = QPushButton("粘贴并编码")

        def url_string_paste_encode():
            self.e_url_string.setText(QApplication.clipboard().text())
            url_string_encode()

        self.b_url_string_paste_encode.clicked.connect(url_string_paste_encode)

        self.b_url_string_clear = QPushButton("清空")

        self.b_url_string_clear.clicked.connect(self.e_url_string.clear)

        self.box_g_url_string = QGridLayout()
        self.box_g_url_string.addWidget(self.e_url_string, 0, 0, 7, 1)
        self.box_g_url_string.addWidget(self.b_url_string_encode, 1, 1, 1, 1)
        self.box_g_url_string.addWidget(self.b_url_string_decode, 2, 1, 1, 1)
        self.box_g_url_string.addWidget(self.b_url_string_paste_encode, 3, 1,
                                        1, 1)
        self.box_g_url_string.addWidget(self.b_url_string_paste_decode, 4, 1,
                                        1, 1)
        self.box_g_url_string.addWidget(self.b_url_string_clear, 5, 1, 1, 1)
        self.box_g_url_string.addWidget(self.e_url_string_result, 0, 2, 7, 1)

        self.g_url_string = QGroupBox("url编解码")
        self.g_url_string.setLayout(self.box_g_url_string)
        # ======== tap 2 ==============================

        # ======== tap 3 ==============================
        self.l_webservice_test_url = QLabel("WebService Url:")
        self.e_webservice_test_url = QLineEdit()
        self.e_webservice_test_result = QTextEdit()
        self.e_webservice_test_result.setReadOnly(True)
        self.e_webservice_test_result.textChanged.connect(
            lambda: self.e_webservice_test_result.moveCursor(QTextCursor.End))
        self.content_webservice_test = self.e_webservice_test_result.toPlainText(
        )

        self.b_webservice_test = QPushButton("测试webservice")

        def webservice_test():
            client = Client(self.e_webservice_test_url.text(), autoblend=True)
            self.e_webservice_test_result.setText(str(client))

        self.b_webservice_test.clicked.connect(
            lambda: self.catch_to_alert(webservice_test))

        self.l_webservice_test_method = QLabel("方法名:")
        self.e_webservice_test_method = QLineEdit()

        self.box_g_webservice_test_params = QGridLayout()

        self.box_g_webservice_test_params.addWidget(
            self.l_webservice_test_method, 0, 0)
        self.box_g_webservice_test_params.addWidget(
            self.e_webservice_test_method, 0, 1)
        self.params_count = 13
        for i in range(1, self.params_count):
            setattr(self, "l_webservice_test_param%d" % i, QLabel("参数%d" % i))
            setattr(self, "e_webservice_test_param%d" % i, QLineEdit())
            l = getattr(self, "l_webservice_test_param%d" % i)
            e = getattr(self, "e_webservice_test_param%d" % i)
            self.box_g_webservice_test_params.addWidget(l, i, 0)
            self.box_g_webservice_test_params.addWidget(e, i, 1)

        self.s_webservice_test_params = QScrollArea()
        self.s_webservice_test_params.setLayout(
            self.box_g_webservice_test_params)

        self.b_webservice_test_send_request = QPushButton("发送请求")

        def webservice_test_send_request():
            client = Client(self.e_webservice_test_url.text(), autoblend=True)
            method = getattr(client.service,
                             self.e_webservice_test_method.text())
            params = []
            for i in range(1, self.params_count):
                e_param = getattr(self, "e_webservice_test_param%d" % i)
                param = e_param.text()
                params.append(param)
            try:
                resp = method(tuple(params))
            except suds.TypeNotFound:
                resp = method(*params)
            self.content_webservice_test = resp
            result = unquote_plus(
                resp) if self.c_b_webservice_test_result_url_decode.isChecked(
                ) else resp
            self.e_webservice_test_result.setText(result)

        self.b_webservice_test_send_request.clicked.connect(
            lambda: self.catch_to_alert(webservice_test_send_request))

        self.c_b_webservice_test_result_url_decode = QCheckBox("返回结果Url解码")

        def webservice_test_result_url_decode_or_encode():
            result = self.content_webservice_test \
                if not self.c_b_webservice_test_result_url_decode.isChecked() else unquote_plus(
                self.content_webservice_test)
            self.e_webservice_test_result.setText(result)

        self.c_b_webservice_test_result_url_decode.stateChanged.connect(
            lambda: self.catch_to_alert(
                webservice_test_result_url_decode_or_encode))
        self.box_g_webservice_test = QGridLayout()
        self.box_g_webservice_test.addWidget(self.l_webservice_test_url, 0, 0,
                                             1, 1)
        self.box_g_webservice_test.addWidget(self.e_webservice_test_url, 0, 1,
                                             1, 8)
        self.box_g_webservice_test.addWidget(self.b_webservice_test, 0, 9, 1,
                                             1)
        self.box_g_webservice_test.addWidget(self.s_webservice_test_params, 1,
                                             0, 5, 3)
        self.box_g_webservice_test.addWidget(
            self.b_webservice_test_send_request, 3, 3, 1, 1)
        self.box_g_webservice_test.addWidget(
            self.c_b_webservice_test_result_url_decode, 1, 3, 1, 1)
        self.box_g_webservice_test.addWidget(self.e_webservice_test_result, 1,
                                             4, 5, 6)

        self.g_webservice_test = QGroupBox("webservice测试")
        self.g_webservice_test.setLayout(self.box_g_webservice_test)
        # ======== tap 3 ==============================

        # ======== tap 4 ==============================

        self.c_b_box_screen_record_full_screen = QCheckBox("录制全屏")
        self.c_b_box_screen_record_full_screen.setChecked(True)

        self.c_b_box_screen_record_pointer = QCheckBox("录制指针")
        self.c_b_box_screen_record_pointer.setChecked(True)

        self.b_screen_record_select_area = QPushButton("选取区域")
        self.b_screen_record_start = QPushButton("开始录制")
        self.e_screen_record_result = QTextEdit()
        self.e_screen_record_result.setReadOnly(True)
        self.e_screen_record_result.textChanged.connect(
            lambda: self.e_screen_record_result.moveCursor(QTextCursor.End))

        def screen_record_start():
            if not os.path.exists("ffmpeg.exe"):
                self.alert("目录下未找到[ffmpeg.exe]!")
                return
            self.e_screen_record_result.clear()
            if self.t_screen_record_recording.running:
                if self.t_screen_record_recording.is_pause:
                    self.b_screen_record_start.setText("暂停录制")
                    self.t_screen_record_recording.is_pause = False
                else:
                    self.b_screen_record_start.setText("继续录制")
                    self.t_screen_record_recording.is_pause = True
            else:
                self.l_screen_record_time.setText("0s")
                self.b_screen_record_start.setText("暂停录制")
            self.c_b_box_screen_record_pointer.setEnabled(False)
            self.c_b_box_screen_record_full_screen.setEnabled(False)
            self.b_screen_record_stop.setEnabled(True)
            self.l_screen_record_time.setVisible(True)
            self.t_screen_record_recording.full_screen = self.c_b_box_screen_record_full_screen.isChecked(
            )
            self.t_screen_record_recording.record_pointer = self.c_b_box_screen_record_pointer.isChecked(
            )
            self.t_screen_record_recording.start()

        self.b_screen_record_start.clicked.connect(screen_record_start)
        self.t_screen_record_recording = ScreenRecordThread()

        self.p_screen_record_save = QProcess()

        self.screen_record_save_path = ""

        def p_screen_record_save_finished(code, status):
            if code == 0:
                self.alert("保存成功>" + self.screen_record_save_path)
            else:
                self.alert("保存失败 code:%s,status:%s" % (code, status))

            screen_record_reset()

        def p_screen_record_save_read():
            self.e_screen_record_result.append(
                str(self.p_screen_record_save.readAllStandardError(),
                    encoding="gbk"))
            self.e_screen_record_result.append(
                str(self.p_screen_record_save.readAllStandardOutput(),
                    encoding="gbk"))

        self.p_screen_record_save.readyReadStandardError.connect(
            p_screen_record_save_read)
        self.p_screen_record_save.readyReadStandardOutput.connect(
            p_screen_record_save_read)
        self.p_screen_record_save.finished.connect(
            p_screen_record_save_finished)

        def screen_record_reset():
            shutil.rmtree(self.t_screen_record_recording.temp_path)
            self.b_screen_record_start.setText("开始录制")
            self.b_screen_record_start.setEnabled(True)
            self.c_b_box_screen_record_pointer.setEnabled(True)
            self.c_b_box_screen_record_full_screen.setEnabled(True)
            self.b_screen_record_stop.setEnabled(False)
            self.l_screen_record_time.clear()
            self.l_screen_record_time.setVisible(False)

        def screen_record_stop(path, fps):
            save_path = QFileDialog.getSaveFileName(self, "保存视频")[0]
            if save_path == "":
                self.alert("取消保存")
                screen_record_reset()
                return
            else:
                if not save_path.endswith(".mp4"):
                    save_path = save_path + ".mp4"
                self.screen_record_save_path = save_path

                self.b_screen_record_start.setEnabled(False)
                command = "./ffmpeg.exe -f image2 -r " + str(
                    fps) + " -i ./" + path + '/%d.jpg -y "' + save_path + '"'

                self.p_screen_record_save.start(command)

        def screen_record_time():
            self.l_screen_record_time.setText(
                str(self.t_screen_record_recording.record_time) + "s")

        self.t_screen_record_recording.stop_trigger.connect(screen_record_stop)
        self.t_screen_record_recording.record_trigger.connect(
            screen_record_time)

        self.b_screen_record_stop = QPushButton("结束录制")
        self.b_screen_record_stop.setEnabled(False)
        self.l_screen_record_time = QLabel()
        self.l_screen_record_time.setVisible(False)

        def screen_record_stop():
            self.b_screen_record_stop.setEnabled(False)
            self.t_screen_record_recording.stop()

        self.b_screen_record_stop.clicked.connect(screen_record_stop)

        self.box_g_screen_record = QGridLayout()
        self.box_g_screen_record.addWidget(self.c_b_box_screen_record_pointer,
                                           0, 0)
        self.box_g_screen_record.addWidget(
            self.c_b_box_screen_record_full_screen, 0, 1)
        self.box_g_screen_record.addWidget(self.b_screen_record_select_area, 0,
                                           2)
        self.box_g_screen_record.addWidget(self.b_screen_record_start, 0, 3)
        self.box_g_screen_record.addWidget(self.b_screen_record_stop, 0, 4)
        self.box_g_screen_record.addWidget(self.l_screen_record_time, 0, 5)
        self.box_g_screen_record.addWidget(self.e_screen_record_result, 1, 0,
                                           1, 10)

        self.g_screen_record = QGroupBox("屏幕录制")
        self.g_screen_record.setLayout(self.box_g_screen_record)
        # ======== tap 4 ==============================

        self.tab_box = QTabWidget()

        self.tab_box.addTab(self.g_img_to_b64str, "base64转换")
        self.tab_box.addTab(self.g_url_string, "url转换")
        self.tab_box.addTab(self.g_webservice_test, "webservice测试")
        self.tab_box.addTab(self.g_screen_record, "屏幕录制")
        # self.tab_box.setTabEnabled(3, False)

        self.box_v_window = QVBoxLayout()
        self.box_v_window.addWidget(self.tab_box)
        self.box_v_window.addWidget(self.l_tips,
                                    alignment=Qt.AlignBottom | Qt.AlignVCenter)

        self.setLayout(self.box_v_window)

        self.resize(900, 500)
        self.setFixedSize(self.size())
        self.setWindowIcon(QIcon(base64_to_pixmap(icon)))
        self.setWindowTitle("Tools v1.0.3 [email protected]/lichun")
コード例 #20
0
ファイル: queues.py プロジェクト: zhoumaomao11/Pymakr
 def hgQueueDeletePurgeActivateQueue(self, name, operation):
     """
     Public method to delete the reference to a queue and optionally
     remove the patch directory or set the active queue.
     
     @param name file/directory name (string)
     @param operation operation to be performed (Queues.QUEUE_DELETE,
         Queues.QUEUE_PURGE, Queues.QUEUE_ACTIVATE)
     @exception ValueError raised to indicate an invalid operation
     """
     # find the root of the repo
     repodir = self.vcs.splitPath(name)[0]
     while not os.path.isdir(os.path.join(repodir, self.vcs.adminDir)):
         repodir = os.path.dirname(repodir)
         if os.path.splitdrive(repodir)[1] == os.sep:
             return
     
     if operation == Queues.QUEUE_PURGE:
         title = self.tr("Purge Queue")
     elif operation == Queues.QUEUE_DELETE:
         title = self.tr("Delete Queue")
     elif operation == Queues.QUEUE_ACTIVATE:
         title = self.tr("Activate Queue")
     else:
         raise ValueError("illegal value for operation")
     
     from .HgQueuesQueueManagementDialog import \
         HgQueuesQueueManagementDialog
     dlg = HgQueuesQueueManagementDialog(
         HgQueuesQueueManagementDialog.QUEUE_INPUT,
         title, True, repodir, self.vcs)
     if dlg.exec_() == QDialog.Accepted:
         queueName = dlg.getData()
         if queueName:
             args = self.vcs.initCommand("qqueue")
             if operation == Queues.QUEUE_PURGE:
                 args.append("--purge")
             elif operation == Queues.QUEUE_DELETE:
                 args.append("--delete")
             args.append(queueName)
             
             client = self.vcs.getClient()
             error = ""
             if client:
                 error = client.runcommand(args)[1]
             else:
                 process = QProcess()
                 process.setWorkingDirectory(repodir)
                 process.start('hg', args)
                 procStarted = process.waitForStarted(5000)
                 if procStarted:
                     finished = process.waitForFinished(30000)
                     if finished:
                         if process.exitCode() != 0:
                             error = str(process.readAllStandardError(),
                                         self.vcs.getEncoding(), 'replace')
             
             if error:
                 if operation == Queues.QUEUE_PURGE:
                     errMsg = self.tr("Error while purging the queue.")
                 elif operation == Queues.QUEUE_DELETE:
                     errMsg = self.tr("Error while deleting the queue.")
                 elif operation == Queues.QUEUE_ACTIVATE:
                     errMsg = self.tr(
                         "Error while setting the active queue.")
                 E5MessageBox.warning(
                     None,
                     title,
                     """<p>{0}</p><p>{1}</p>""".format(errMsg, error))
             else:
                 if self.queuesListQueuesDialog is not None and \
                    self.queuesListQueuesDialog.isVisible():
                     self.queuesListQueuesDialog.refresh()
コード例 #21
0
ファイル: designer.py プロジェクト: Kammann123/sae_fend
""" This Designer script is an utility that can be used to run the Qt Designer tool interface
    adding automatically the environment variables needed to detect the new widget plugins from the project.
"""

# PyQt5 modules
from PyQt5.QtCore import QProcess, QProcessEnvironment

# Python modules
import os

if __name__ == "__main__":
    designer_bin = 'designer'

    plugin_path = os.path.join(os.path.dirname(__file__), 'plugins')
    widget_path = os.path.join(os.path.dirname(__file__), 'src', 'widgets')
    custom_path = os.path.join(os.path.dirname(__file__), 'src')
    project_path = os.path.join(os.path.dirname(__file__))

    env = QProcessEnvironment.systemEnvironment()
    env.insert('PYQTDESIGNERPATH', plugin_path)
    env.insert('PYTHONPATH', f"{widget_path};{custom_path};{project_path}")

    designer = QProcess()
    designer.setProcessEnvironment(env)
    designer.start(designer_bin)
    designer.waitForFinished(-1)
    designer.exitCode()
コード例 #22
0
ファイル: ProgramsDialog.py プロジェクト: zhoumaomao11/Pymakr
 def __createProgramEntry(self,
                          description,
                          exe,
                          versionCommand="",
                          versionStartsWith="",
                          versionPosition=0,
                          version="",
                          versionCleanup=None,
                          versionRe=None):
     """
     Private method to generate a program entry.
     
     @param description descriptive text (string)
     @param exe name of the executable program (string)
     @param versionCommand command line switch to get the version info
         (string) if this is empty, the given version will be shown.
     @param versionStartsWith start of line identifying version info
         (string)
     @param versionPosition index of part containing the version info
         (integer)
     @keyparam version version string to show (string)
     @keyparam versionCleanup tuple of two integers giving string positions
         start and stop for the version string (tuple of integers)
     @keyparam versionRe regexp to determine the line identifying version
         info (string). Takes precedence over versionStartsWith.
     @return version string of detected or given version (string)
     """
     itmList = self.programsList.findItems(description,
                                           Qt.MatchCaseSensitive)
     if itmList:
         itm = itmList[0]
     else:
         itm = QTreeWidgetItem(self.programsList, [description])
     font = itm.font(0)
     font.setBold(True)
     itm.setFont(0, font)
     if not exe:
         itm.setText(1, self.tr("(not configured)"))
     else:
         if os.path.isabs(exe):
             if not Utilities.isExecutable(exe):
                 exe = ""
         else:
             exe = Utilities.getExecutablePath(exe)
         if exe:
             if versionCommand and \
                (versionStartsWith != "" or
                 (versionRe is not None and versionRe != "")) and \
                versionPosition:
                 proc = QProcess()
                 proc.setProcessChannelMode(QProcess.MergedChannels)
                 proc.start(exe, [versionCommand])
                 finished = proc.waitForFinished(10000)
                 if finished:
                     output = str(proc.readAllStandardOutput(),
                                  Preferences.getSystem("IOEncoding"),
                                  'replace')
                     if versionRe is None:
                         versionRe = "^{0}".format(
                             re.escape(versionStartsWith))
                     versionRe = re.compile(versionRe, re.UNICODE)
                     for line in output.splitlines():
                         if versionRe.search(line):
                             try:
                                 version = line.split()[versionPosition]
                                 if versionCleanup:
                                     version = version[versionCleanup[0]:
                                                       versionCleanup[1]]
                                 break
                             except IndexError:
                                 version = self.tr("(unknown)")
                     else:
                         version = self.tr("(unknown)")
                 else:
                     version = self.tr("(not executable)")
             QTreeWidgetItem(itm, [exe, version])
             itm.setExpanded(True)
         else:
             itm.setText(1, self.tr("(not found)"))
     QApplication.processEvents()
     self.programsList.header().resizeSections(QHeaderView.ResizeToContents)
     self.programsList.header().setStretchLastSection(True)
     return version
コード例 #23
0
ファイル: queues.py プロジェクト: zhoumaomao11/Pymakr
 def hgQueueCreateRenameQueue(self, name, isCreate):
     """
     Public method to create a new queue or rename the active queue.
     
     @param name file/directory name (string)
     @param isCreate flag indicating to create a new queue (boolean)
     """
     # find the root of the repo
     repodir = self.vcs.splitPath(name)[0]
     while not os.path.isdir(os.path.join(repodir, self.vcs.adminDir)):
         repodir = os.path.dirname(repodir)
         if os.path.splitdrive(repodir)[1] == os.sep:
             return
     
     if isCreate:
         title = self.tr("Create New Queue")
     else:
         title = self.tr("Rename Active Queue")
     from .HgQueuesQueueManagementDialog import \
         HgQueuesQueueManagementDialog
     dlg = HgQueuesQueueManagementDialog(
         HgQueuesQueueManagementDialog.NAME_INPUT,
         title, False, repodir, self.vcs)
     if dlg.exec_() == QDialog.Accepted:
         queueName = dlg.getData()
         if queueName:
             args = self.vcs.initCommand("qqueue")
             if isCreate:
                 args.append("--create")
             else:
                 args.append("--rename")
             args.append(queueName)
             
             client = self.vcs.getClient()
             error = ""
             if client:
                 error = client.runcommand(args)[1]
             else:
                 process = QProcess()
                 process.setWorkingDirectory(repodir)
                 process.start('hg', args)
                 procStarted = process.waitForStarted(5000)
                 if procStarted:
                     finished = process.waitForFinished(30000)
                     if finished:
                         if process.exitCode() != 0:
                             error = str(process.readAllStandardError(),
                                         self.vcs.getEncoding(), 'replace')
             
             if error:
                 if isCreate:
                     errMsg = self.tr(
                         "Error while creating a new queue.")
                 else:
                     errMsg = self.tr(
                         "Error while renaming the active queue.")
                 E5MessageBox.warning(
                     None,
                     title,
                     """<p>{0}</p><p>{1}</p>""".format(errMsg, error))
             else:
                 if self.queuesListQueuesDialog is not None and \
                    self.queuesListQueuesDialog.isVisible():
                     self.queuesListQueuesDialog.refresh()
コード例 #24
0
    def __init__(self, aPath, parent=None):
        super(VideoPlayer, self).__init__(parent)

        self.setAttribute(Qt.WA_NoSystemBackground, True)
        self.setAcceptDrops(True)
        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.StreamPlayback)
        self.mediaPlayer.mediaStatusChanged.connect(self.printMediaData)
        self.mediaPlayer.setVolume(80)
        self.videoWidget = QVideoWidget(self)

        self.lbl = QLineEdit('00:00:00')
        self.lbl.setReadOnly(True)
        self.lbl.setFixedWidth(70)
        self.lbl.setUpdatesEnabled(True)
        self.lbl.setStyleSheet(stylesheet(self))

        self.elbl = QLineEdit('00:00:00')
        self.elbl.setReadOnly(True)
        self.elbl.setFixedWidth(70)
        self.elbl.setUpdatesEnabled(True)
        self.elbl.setStyleSheet(stylesheet(self))

        self.playButton = QPushButton()
        self.playButton.setEnabled(False)
        self.playButton.setFixedWidth(32)
        self.playButton.setStyleSheet("background-color: black")
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)

        self.positionSlider = QSlider(Qt.Horizontal, self)
        self.positionSlider.setStyleSheet(stylesheet(self))
        self.positionSlider.setRange(0, 100)
        self.positionSlider.sliderMoved.connect(self.setPosition)
        self.positionSlider.sliderMoved.connect(self.handleLabel)
        self.positionSlider.setSingleStep(2)
        self.positionSlider.setPageStep(20)
        self.positionSlider.setAttribute(Qt.WA_TranslucentBackground, True)

        self.clip = QApplication.clipboard()
        self.process = QProcess(self)
        self.process.readyRead.connect(self.dataReady)
        #        self.process.started.connect(lambda: print("grabbing YouTube URL"))
        self.process.finished.connect(self.playFromURL)

        self.myurl = ""

        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(5, 0, 5, 0)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.lbl)
        controlLayout.addWidget(self.positionSlider)
        controlLayout.addWidget(self.elbl)

        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.videoWidget)
        layout.addLayout(controlLayout)

        self.setLayout(layout)

        self.myinfo = "©2016\nAxel Schneider\n\nMouse Wheel = Zoom\nUP = Volume Up\nDOWN = Volume Down\n" + \
            "LEFT = < 1 Minute\nRIGHT = > 1 Minute\n" + \
                "SHIFT+LEFT = < 10 Minutes\nSHIFT+RIGHT = > 10 Minutes"

        self.widescreen = True

        #### shortcuts ####
        self.shortcut = QShortcut(QKeySequence("q"), self)
        self.shortcut.activated.connect(self.handleQuit)
        self.shortcut = QShortcut(QKeySequence("u"), self)
        self.shortcut.activated.connect(self.playFromURL)

        self.shortcut = QShortcut(QKeySequence("y"), self)
        self.shortcut.activated.connect(self.getYTUrl)

        self.shortcut = QShortcut(QKeySequence("o"), self)
        self.shortcut.activated.connect(self.openFile)
        self.shortcut = QShortcut(QKeySequence(" "), self)
        self.shortcut.activated.connect(self.play)
        self.shortcut = QShortcut(QKeySequence("f"), self)
        self.shortcut.activated.connect(self.handleFullscreen)
        self.shortcut = QShortcut(QKeySequence("i"), self)
        self.shortcut.activated.connect(self.handleInfo)
        self.shortcut = QShortcut(QKeySequence("s"), self)
        self.shortcut.activated.connect(self.toggleSlider)
        self.shortcut = QShortcut(QKeySequence(Qt.Key_Right), self)
        self.shortcut.activated.connect(self.forwardSlider)
        self.shortcut = QShortcut(QKeySequence(Qt.Key_Left), self)
        self.shortcut.activated.connect(self.backSlider)
        self.shortcut = QShortcut(QKeySequence(Qt.Key_Up), self)
        self.shortcut.activated.connect(self.volumeUp)
        self.shortcut = QShortcut(QKeySequence(Qt.Key_Down), self)
        self.shortcut.activated.connect(self.volumeDown)
        self.shortcut = QShortcut(
            QKeySequence(Qt.ShiftModifier + Qt.Key_Right), self)
        self.shortcut.activated.connect(self.forwardSlider10)
        self.shortcut = QShortcut(QKeySequence(Qt.ShiftModifier + Qt.Key_Left),
                                  self)
        self.shortcut.activated.connect(self.backSlider10)

        self.mediaPlayer.setVideoOutput(self.videoWidget)
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.positionChanged.connect(self.handleLabel)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
        self.mediaPlayer.error.connect(self.handleError)

        print("QT5 Player started")
        self.suspend_screensaver()
        #        msg = QMessageBox.information(self, "Qt5Player", "press o to open file")
        self.loadFilm("/home/brian/Dokumente/Qt5PlayerIntro.m4v")
コード例 #25
0
    def _performMonitor(self):
        """
        Protected method implementing the monitoring action.
        
        This method populates the statusList member variable
        with a list of strings giving the status in the first column and the
        path relative to the project directory starting with the third column.
        The allowed status flags are:
        <ul>
            <li>"A" path was added but not yet comitted</li>
            <li>"M" path has local changes</li>
            <li>"O" path was removed</li>
            <li>"R" path was deleted and then re-added</li>
            <li>"U" path needs an update</li>
            <li>"Z" path contains a conflict</li>
            <li>" " path is back at normal</li>
        </ul>
        
        @return tuple of flag indicating successful operation (boolean) and
            a status message in case of non successful operation (string)
        """
        self.shouldUpdate = False

        if self.__client is None and not self.__useCommandLine:
            if self.vcs.version >= (2, 9, 9):
                # versions below that have a bug causing a second
                # instance to not recognize changes to the status
                from .HgClient import HgClient
                client = HgClient(self.projectDir, "utf-8", self.vcs)
                ok, err = client.startServer()
                if ok:
                    self.__client = client
                else:
                    self.__useCommandLine = True
            else:
                self.__useCommandLine = True

        # step 1: get overall status
        args = self.vcs.initCommand("status")
        args.append('--noninteractive')
        args.append('--all')

        output = ""
        error = ""
        if self.__client:
            output, error = self.__client.runcommand(args)
        else:
            process = QProcess()
            process.setWorkingDirectory(self.projectDir)
            process.start('hg', args)
            procStarted = process.waitForStarted(5000)
            if procStarted:
                finished = process.waitForFinished(300000)
                if finished and process.exitCode() == 0:
                    output = str(process.readAllStandardOutput(),
                                 self.vcs.getEncoding(), 'replace')
                else:
                    process.kill()
                    process.waitForFinished()
                    error = str(process.readAllStandardError(),
                                self.vcs.getEncoding(), 'replace')
            else:
                process.kill()
                process.waitForFinished()
                error = self.tr("Could not start the Mercurial process.")

        if error:
            return False, error

        states = {}
        for line in output.splitlines():
            if not line.startswith("  "):
                flag, name = line.split(" ", 1)
                if flag in "AMR":
                    if flag == "R":
                        status = "O"
                    else:
                        status = flag
                    states[name] = status

        # step 2: get conflicting changes
        args = self.vcs.initCommand("resolve")
        args.append('--list')

        output = ""
        error = ""
        if self.__client:
            output, error = self.__client.runcommand(args)
        else:
            process.setWorkingDirectory(self.projectDir)
            process.start('hg', args)
            procStarted = process.waitForStarted(5000)
            if procStarted:
                finished = process.waitForFinished(300000)
                if finished and process.exitCode() == 0:
                    output = str(process.readAllStandardOutput(),
                                 self.vcs.getEncoding(), 'replace')

        for line in output.splitlines():
            flag, name = line.split(" ", 1)
            if flag == "U":
                states[name] = "Z"  # conflict

        # step 3: collect the status to be reported back
        for name in states:
            try:
                if self.reportedStates[name] != states[name]:
                    self.statusList.append("{0} {1}".format(
                        states[name], name))
            except KeyError:
                self.statusList.append("{0} {1}".format(states[name], name))
        for name in self.reportedStates.keys():
            if name not in states:
                self.statusList.append("  {0}".format(name))
        self.reportedStates = states

        return True, \
            self.tr("Mercurial status checked successfully")
コード例 #26
0
    def start_process(self,
                      script_name,
                      working_directory,
                      interactive=True,
                      debugger=False,
                      command_args=None,
                      envars=None,
                      runner=None):
        """
        Start the child Python process.

        Will run the referenced Python script_name within the context of the
        working directory.

        If interactive is True (the default) the Python process will run in
        interactive mode (dropping the user into the REPL when the script
        completes).

        If debugger is True (the default is False) then the script will run
        within a debug runner session.

        If there is a list of command_args (the default is None), then these
        will be passed as further arguments into the script to be run.

        If there is a list of environment variables, these will be part of the
        context of the new child process.

        If runner is give, this is used as the command to start the Python
        process.
        """
        self.script = os.path.abspath(os.path.normcase(script_name))
        logger.info('Running script: {}'.format(self.script))
        if interactive:
            logger.info('Running with interactive mode.')
        if command_args is None:
            command_args = []
        logger.info('Command args: {}'.format(command_args))
        self.process = QProcess(self)
        self.process.setProcessChannelMode(QProcess.MergedChannels)
        # Force buffers to flush immediately.
        env = QProcessEnvironment.systemEnvironment()
        env.insert('PYTHONUNBUFFERED', '1')
        if envars:
            logger.info('Running with environment variables: '
                        '{}'.format(envars))
            for name, value in envars:
                env.insert(name, value)
        logger.info('Working directory: {}'.format(working_directory))
        self.process.setWorkingDirectory(working_directory)
        self.process.setProcessEnvironment(env)
        self.process.readyRead.connect(self.read_from_stdout)
        self.process.finished.connect(self.finished)
        logger.info('Python path: {}'.format(sys.path))
        if debugger:
            # Start the mu-debug runner for the script.
            args = [
                self.script,
            ] + command_args
            self.process.start('mu-debug', args)
        else:
            if runner:
                # Use the passed in Python "runner" to run the script.
                python_exec = runner
            else:
                # Use the current system Python to run the script.
                python_exec = sys.executable
            if interactive:
                # Start the script in interactive Python mode.
                args = [
                    '-i',
                    self.script,
                ] + command_args
            else:
                # Just run the command with no additional flags.
                args = [
                    self.script,
                ] + command_args
            self.process.start(python_exec, args)
            self.running = True
コード例 #27
0
ファイル: tivopy.py プロジェクト: emanuel-mazilu/TIVOpy
    def __init__(self, aPath, parent=None):
        super(VideoPlayer, self).__init__(parent)

        self.setAttribute(Qt.WA_NoSystemBackground, True)
        self.setAcceptDrops(True)
        
        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.StreamPlayback)
        self.mediaPlayer.setVolume(80)
        
        self.videoWidget = QVideoWidget(self)
        self.videoWidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.videoWidget.setMinimumSize(QSize(640, 360))
        
        self.lbl = QLineEdit('00:00:00')
        self.lbl.setReadOnly(True)
        self.lbl.setFixedWidth(70)
        self.lbl.setUpdatesEnabled(True)
        self.lbl.setStyleSheet(stylesheet(self))

        self.elbl = QLineEdit('00:00:00')
        self.elbl.setReadOnly(True)
        self.elbl.setFixedWidth(70)
        self.elbl.setUpdatesEnabled(True)
        self.elbl.setStyleSheet(stylesheet(self))

        self.playButton = QPushButton()
        self.playButton.setEnabled(False)
        self.playButton.setFixedWidth(32)
        self.playButton.setStyleSheet("background-color: black")
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)

        self.positionSlider = QSlider(Qt.Horizontal, self)
        self.positionSlider.setStyleSheet(stylesheet(self))
        self.positionSlider.setRange(0, 100)
        self.positionSlider.sliderMoved.connect(self.setPosition)
        self.positionSlider.sliderMoved.connect(self.handleLabel)
        self.positionSlider.setSingleStep(2)
        self.positionSlider.setPageStep(20)
        self.positionSlider.setAttribute(Qt.WA_TranslucentBackground, True)

        self.clip = QApplication.clipboard()
        self.process = QProcess(self)
        self.process.readyRead.connect(self.dataReady)
        self.process.finished.connect(self.playFromURL)

        self.myurl = ""

        # channel list
        self.channelList = QListView(self)
        self.channelList.setMinimumSize(QSize(150, 0))
        self.channelList.setMaximumSize(QSize(150, 4000))
        self.channelList.setFrameShape(QFrame.Box)
        self.channelList.setObjectName("channelList")
        self.channelList.setStyleSheet("background-color: black; color: #585858;")
        self.channelList.setFocus()
        # for adding items to list must create a model
        self.model = QStandardItemModel()
        self.channelList.setModel(self.model)

        self.controlLayout = QHBoxLayout()
        self.controlLayout.setContentsMargins(5, 0, 5, 0)
        self.controlLayout.addWidget(self.playButton)
        self.controlLayout.addWidget(self.lbl)
        self.controlLayout.addWidget(self.positionSlider)
        self.controlLayout.addWidget(self.elbl)

        self.mainLayout = QHBoxLayout()

        # contains video and cotrol widgets to the left side
        self.layout = QVBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.addWidget(self.videoWidget)
        self.layout.addLayout(self.controlLayout)
        
        # adds channels list to the right
        self.mainLayout.addLayout(self.layout)
        self.mainLayout.addWidget(self.channelList)

        self.setLayout(self.mainLayout)

        self.myinfo = "©2020\nTIVOpy v1.0"

        self.widescreen = True

        #### shortcuts ####
        self.shortcut = QShortcut(QKeySequence("q"), self)
        self.shortcut.activated.connect(self.handleQuit)
        self.shortcut = QShortcut(QKeySequence("u"), self)
        self.shortcut.activated.connect(self.playFromURL)
        self.shortcut = QShortcut(QKeySequence(Qt.Key_Space), self)
        self.shortcut.activated.connect(self.play)
        self.shortcut = QShortcut(QKeySequence(Qt.Key_F), self)
        self.shortcut.activated.connect(self.handleFullscreen)
        self.shortcut = QShortcut(QKeySequence(Qt.Key_Escape), self)
        self.shortcut.activated.connect(self.exitFullscreen)
        self.shortcut.activated.connect(self.handleFullscreen)
        self.shortcut = QShortcut(QKeySequence("i"), self)
        self.shortcut.activated.connect(self.handleInfo)
        self.shortcut = QShortcut(QKeySequence("s"), self)
        self.shortcut.activated.connect(self.toggleSlider)
        self.shortcut = QShortcut(QKeySequence(Qt.Key_Right), self)
        self.shortcut.activated.connect(self.forwardSlider)
        self.shortcut = QShortcut(QKeySequence(Qt.Key_Left), self)
        self.shortcut.activated.connect(self.backSlider)

        self.mediaPlayer.setVideoOutput(self.videoWidget)
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.positionChanged.connect(self.handleLabel)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
        self.mediaPlayer.error.connect(self.handleError)

        self.populateChannelList()
        self.selectChannel()
        self.initialPlay()
コード例 #28
0
ファイル: Conda.py プロジェクト: skeptycal/eric6-20.3
    def searchPackages(self,
                       pattern,
                       fullNameOnly=False,
                       packageSpec=False,
                       platform="",
                       name="",
                       prefix=""):
        """
        Public method to search for a package pattern of a conda environment.
        
        @param pattern package search pattern
        @type str
        @param fullNameOnly flag indicating to search for full names only
        @type bool
        @param packageSpec flag indicating to search a package specification
        @type bool
        @param platform type of platform to be searched for
        @type str
        @param name name of the environment
        @type str
        @param prefix prefix of the environment
        @type str
        @return flag indicating success and a dictionary with package name as
            key and list of dictionaries containing detailed data for the found
            packages as values
        @rtype tuple of (bool, dict of list of dict)
        @exception RuntimeError raised to indicate an error in parameters
        
        Note: only one of name or prefix must be given.
        """
        if name and prefix:
            raise RuntimeError("Only one of 'name' or 'prefix' must be given.")

        args = [
            "search",
            "--json",
        ]
        if fullNameOnly:
            args.append("--full-name")
        if packageSpec:
            args.append("--spec")
        if platform:
            args.extend(["--platform", platform])
        if name:
            args.extend(["--name", name])
        elif prefix:
            args.extend(["--prefix", prefix])
        args.append(pattern)

        exe = Preferences.getConda("CondaExecutable")
        if not exe:
            exe = "conda"

        packages = {}
        ok = False

        proc = QProcess()
        proc.start(exe, args)
        if proc.waitForStarted(15000):
            if proc.waitForFinished(30000):
                output = str(proc.readAllStandardOutput(),
                             Preferences.getSystem("IOEncoding"),
                             'replace').strip()
                try:
                    packages = json.loads(output)
                    ok = "error" not in packages
                except Exception:
                    # return values for errors is already set
                    pass

        return ok, packages
コード例 #29
0
ファイル: Conda.py プロジェクト: skeptycal/eric6-20.3
    def getUpdateablePackages(self, name="", prefix=""):
        """
        Public method to get a list of updateable packages of a conda
        environment.
        
        @param name name of the environment
        @type str
        @param prefix prefix of the environment
        @type str
        @return list of installed packages. Each entry is a tuple containing
            the package name, version and build.
        @rtype list of tuples of (str, str, str)
        @exception RuntimeError raised to indicate an error in parameters
        
        Note: only one of name or prefix must be given.
        """
        if name and prefix:
            raise RuntimeError("Only one of 'name' or 'prefix' must be given.")

        if not name and not prefix:
            raise RuntimeError("One of 'name' or 'prefix' must be given.")

        args = [
            "update",
            "--json",
            "--quiet",
            "--all",
            "--dry-run",
        ]
        if name:
            args.extend(["--name", name])
        elif prefix:
            args.extend(["--prefix", prefix])

        exe = Preferences.getConda("CondaExecutable")
        if not exe:
            exe = "conda"

        packages = []

        proc = QProcess()
        proc.start(exe, args)
        if proc.waitForStarted(15000):
            if proc.waitForFinished(30000):
                output = str(proc.readAllStandardOutput(),
                             Preferences.getSystem("IOEncoding"),
                             'replace').strip()
                try:
                    jsonDict = json.loads(output)
                except Exception:
                    jsonDict = {}

                if "actions" in jsonDict and "LINK" in jsonDict["actions"]:
                    for linkEntry in jsonDict["actions"]["LINK"]:
                        if isinstance(linkEntry, dict):
                            packages.append(
                                (linkEntry["name"], linkEntry["version"],
                                 linkEntry["build_string"]))
                        else:
                            package = linkEntry.split()[0]
                            parts = package.rsplit("-", 2)
                            while len(parts) < 3:
                                parts.append("")
                            packages.append(tuple(parts))

        return packages
コード例 #30
0
ファイル: Conda.py プロジェクト: skeptycal/eric6-20.3
    def removeCondaEnvironment(self, name="", prefix=""):
        """
        Public method to remove a conda environment.
        
        @param name name of the environment
        @type str
        @param prefix prefix of the environment
        @type str
        @return flag indicating success
        @rtype bool
        @exception RuntimeError raised to indicate an error in parameters
        
        Note: only one of name or prefix must be given.
        """
        if name and prefix:
            raise RuntimeError("Only one of 'name' or 'prefix' must be given.")

        if not name and not prefix:
            raise RuntimeError("One of 'name' or 'prefix' must be given.")

        args = [
            "remove",
            "--json",
            "--quiet",
            "--all",
        ]
        if name:
            args.extend(["--name", name])
        elif prefix:
            args.extend(["--prefix", prefix])

        exe = Preferences.getConda("CondaExecutable")
        if not exe:
            exe = "conda"

        proc = QProcess()
        proc.start(exe, args)
        if not proc.waitForStarted(15000):
            E5MessageBox.critical(
                self.__ui, self.tr("conda remove"),
                self.tr("""The conda executable could not be started."""))
            return False
        else:
            proc.waitForFinished(15000)
            output = str(proc.readAllStandardOutput(),
                         Preferences.getSystem("IOEncoding"),
                         'replace').strip()
            try:
                jsonDict = json.loads(output)
            except Exception:
                E5MessageBox.critical(
                    self.__ui, self.tr("conda remove"),
                    self.tr("""The conda executable returned invalid data."""))
                return False

            if "error" in jsonDict:
                E5MessageBox.critical(
                    self.__ui, self.tr("conda remove"),
                    self.tr("<p>The conda executable returned an error.</p>"
                            "<p>{0}</p>").format(jsonDict["message"]))
                return False

            if jsonDict["success"]:
                self.condaEnvironmentRemoved.emit()

            return jsonDict["success"]

        return False