예제 #1
0
    def __init__(self):

        self.motivoProcess = QProcess()

        self.buildProcess = QProcess()
        self.mergeProcess = QProcess()
        self.sampleProcess = QProcess()

        self.graphProcess = QProcess()

        # TODO check motivo directory and produce an error message if needed
        self.motivoProcess.setWorkingDirectory(MotivoAccess.motivoDirectory +
                                               '/scripts/')
        self.motivoProcess.setProgram('motivo.sh')
        # Qproces emit readReady signal when data is ready to be read
        # Connect the handler for read the data

        self.buildProcess.setWorkingDirectory(MotivoAccess.motivoDirectory +
                                              '/build/bin/')
        self.buildProcess.setProgram('motivo-build')

        self.mergeProcess.setWorkingDirectory(MotivoAccess.motivoDirectory +
                                              '/build/bin/')
        self.mergeProcess.setProgram('motivo-merge')

        self.sampleProcess.setWorkingDirectory(MotivoAccess.motivoDirectory +
                                               '/build/bin/')
        self.sampleProcess.setProgram('motivo-sample')

        self.graphProcess.setWorkingDirectory(MotivoAccess.motivoDirectory +
                                              '/build/bin/')
        self.graphProcess.setProgram('motivo-graph')
    def execute(self, command, parsers=no_parsers):
        """
        Enqueue a worker to run (at some point) by passing it to the QThreadPool.
        """

        job_id = uuid.uuid4().hex

        # By default, the signals do not have access to any information about
        # the process that sent it. So we use this constructor to annotate
        #  each signal with a job_id.

        def fwd_signal(target):
            return lambda *args: target(job_id, *args)

        self._parsers[job_id] = parsers

        # Set default status to waiting, 0 progress.
        self._state[job_id] = DEFAULT_STATE.copy()

        p = QProcess()
        p.readyReadStandardOutput.connect(fwd_signal(self.handle_output))
        p.readyReadStandardError.connect(fwd_signal(self.handle_output))
        p.stateChanged.connect(fwd_signal(self.handle_state))
        p.finished.connect(fwd_signal(self.done))

        self._jobs[job_id] = p

        p.start(command)

        self.layoutChanged.emit()
예제 #3
0
파일: scans2pdfgui.py 프로젝트: Unrud/djpdf
    def save(self, url):
        self._saving = True
        self.savingChanged.emit()
        self._savingProgress = 0
        self.savingProgressChanged.emit()
        p = QProcess(self)
        p.setProcessChannelMode(QProcess.ForwardedErrorChannel)

        stdout_buffer = b""

        def ready_read_stdout():
            nonlocal stdout_buffer
            stdout_buffer += p.readAllStandardOutput().data()
            *messages, stdout_buffer = stdout_buffer.split(b"\n")
            for message in messages:
                progress = json.loads(messages[-1].decode())
                self._savingProgress = progress["fraction"]
                self.savingProgressChanged.emit()
        p.readyReadStandardOutput.connect(ready_read_stdout)
        p.finished.connect(self._process_finished)
        args = ["-c", "from djpdf.scans2pdf import main; main()",
                os.path.abspath(url.toLocalFile())]
        if self._verbose:
            args.append("--verbose")
        p.start(sys.executable, args)
        self._process = p
        p.write(json.dumps([p._data for p in self._pages]).encode())
        p.closeWriteChannel()
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle(APP_NAME)
        self.setWindowIcon(QIcon(get_resource_path(os.path.join('resources', 'noun_Plant.ico'))))
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.ui.lineEdit_invoiceNumber.setValidator(QIntValidator())
        self.ui.progressBar.setMaximum(1)
        self.proc = QProcess()

        self.ui.tableWidget_invoiceContent.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.savePath = create_path_it_not_exist(os.path.join(get_config_path(APP_CONFIG_FOLDER), 'save.json'))
        self.saveData = SaveData(self.savePath)
        self.outputPath = os.path.join(get_exe_path(), create_path_it_not_exist(os.path.join(get_exe_path(), 'output')))
        self.texGenerator = LatexTemplateGenerator(get_resource_path('resources').replace('\\', '/'))

        self.currentGeneralInfo = GeneralInfo()
        self.currentClientInfo = ClientInfo()
        self.currentInvoiceInfo = InvoiceInfo()

        self.ui.pushButton_saveQuickRecallInvoice.clicked.connect(self.save_invoice_info)
        self.ui.pushButton_saveQuickRecallClient.clicked.connect(self.save_client_info)
        self.ui.pushButton_saveQuickRecallGeneral.clicked.connect(self.save_general_info)

        self.ui.comboBox_quickRecallInvoice.activated.connect(self.on_combo_box_invoice_changed)
        self.ui.comboBox_quickRecallClient.activated.connect(self.on_combo_box_client_changed)
        self.ui.comboBox_quickRecallGeneral.activated.connect(self.on_combo_box_general_changed)

        self.ui.pushButton_generateInvoice.clicked.connect(self.generate_invoice)

        self.proc.finished.connect(functools.partial(self._handleProcFinished, self.proc))

        self.ui.toolButton_add.clicked.connect(self.add_row)
        self.ui.toolButton_delete.clicked.connect(self.delete_row)
        self.update_ui()
예제 #5
0
    def run_command(self, cmd: str):
        log.info(
            'run_command',
            program=self.program,
            args=self.args,
            cmd=cmd
        )
        self.output.append(f'> {cmd}\n')
        self.input.clear()

        process = QProcess()
        process.setProgram(self.program)
        process.setCurrentReadChannel(0)

        # noinspection PyUnresolvedReferences
        process.readyReadStandardError.connect(
            lambda: self.handle_error(process)
        )
        # noinspection PyUnresolvedReferences
        process.readyReadStandardOutput.connect(
            lambda: self.handle_output(process)
        )

        connect_args = list(self.args)

        args = cmd.split(' ')
        if args[0] == self.program.split('/')[-1]:
            args.pop(0)
        process.setArguments(connect_args + args)
        process.start()
예제 #6
0
    def compress_file(self, input_file_path: str, quality: str) -> None:

        self.input_file_path = input_file_path.replace("file://", "")

        if not self.is_pdf_file():
            error_message = "Error: Input file is not a PDF"
            self.compressionResult.emit(("error", error_message))
            return

        compression_quality = self.parse_compression_quality(quality)

        binary_path = os.path.join(get_current_dir(), "vendor", "ghostscript",
                                   "bin", "gs")

        self.temp_output_file_path = os.path.join(
            gettempdir(), os.path.basename(self.input_file_path))

        program = f"{binary_path}"
        arguments = [
            "-sDEVICE=pdfwrite",
            "-dCompatibilityLevel=1.4",
            f"-dPDFSETTINGS={compression_quality.value}",
            "-dNOPAUSE",
            "-dQUIET",
            "-dBATCH",
            f"-sOutputFile={self.temp_output_file_path}",
            self.input_file_path,
        ]

        self.process = QProcess()
        self.process.start(program, arguments)
        self.process.finished.connect(self.send_result)
        self.process.errorOccurred.connect(
            lambda error: self.compressionResult.emit(("error", str(error))))
예제 #7
0
 def __init__(self, home, app_name=None):
     super(self.__class__, self).__init__()
     self.setupUi(self)
     self.setStyleSheet(qss)
     self.home = home
     self.interpreter = None
     self.p = QProcess()
     self.thread_pool = QThreadPool()
     # btn
     self.py_setting_btn.clicked.connect(self.py_setting_slot)
     self.set_app_py.clicked.connect(self.set_app_py_slot)
     #
     self.py_box.currentTextChanged.connect(self.py_change_slot)
     self.pip_list.setContextMenuPolicy(Qt.CustomContextMenu)
     self.pip_list.customContextMenuRequested.connect(self.generate_menu)  ####右键菜单
     #
     self.load_py()
     if not app_name:
         """用于设置窗口"""
         self.app_name.hide()
         self.set_app_py.hide()
         self.cur_py.hide()
         self.label_3.hide()
     else:
         """用于应用窗口"""
         self.app_name.setText(app_name)
         self.app_name.setStyleSheet("""color:#BE9117""")
         self.cur_py.setStyleSheet("""color:#168AD5""")
         path = G.config.installed_apps[app_name].get('py_', '未选择')
         for name, p in G.config.python_path.items():
             if path == p:
                 self.cur_py.setText(name)
             else:
                 self.cur_py.setText(path)
예제 #8
0
 def testNoArgs(self):
     '''Connecting a lambda to a signal without arguments'''
     proc = QProcess()
     dummy = Dummy()
     QObject.connect(proc, SIGNAL('started()'),
                     lambda: setattr(dummy, 'called', True))
     proc.start(sys.executable, ['-c', '""'])
     proc.waitForFinished()
     self.assert_(dummy.called)
예제 #9
0
    def __init__(self, fileName, parent=None):
        super(Form, self).__init__(parent)
        self._fileName = fileName

        self.setStyleSheet("font-family: Source Code Pro; font-size: 16px; ")

        self._process = QProcess()
        self._process.readyReadStandardOutput.connect(self._processStdOut)
        self._process.readyReadStandardError.connect(self._processStdErr)
        self._process.finished.connect(self._processFinished)
예제 #10
0
 def start_qt_process(self, cmd):
     """
     启动子进程执行耗时命令
     :param cmd:
     :return:
     """
     process = QProcess(self.ui)
     process.start(cmd)
     result = process.waitForStarted()
     return result
예제 #11
0
    def start(self):
        if self.p is not None:
            return

        self.p = QProcess()
        self.p.readyReadStandardOutput.connect(self.handle_stdout)
        self.p.readyReadStandardError.connect(self.handle_stderr)
        self.p.stateChanged.connect(self.handle_state)
        self.p.finished.connect(self.cleanup)
        self.p.start("python", ["dummy_script.py"])
예제 #12
0
파일: scans2pdfgui.py 프로젝트: Unrud/djpdf
    def save(self, url):
        self._saving = True
        self.savingChanged.emit()
        self._savingProgress = 0
        self.savingProgressChanged.emit()
        p = QProcess(self)
        p.setProcessChannelMode(QProcess.ForwardedErrorChannel)

        stdout_buffer = b""

        def ready_read_stdout():
            nonlocal stdout_buffer
            stdout_buffer += p.readAllStandardOutput().data()
            *messages, stdout_buffer = stdout_buffer.split(b"\n")
            for message in messages:
                progress = json.loads(messages[-1].decode())
                self._savingProgress = progress["fraction"]
                self.savingProgressChanged.emit()
        p.readyReadStandardOutput.connect(ready_read_stdout)

        def finished(status):
            self._saving = False
            self.savingChanged.emit()
            if status != 0:
                self.savingError.emit()
        p.finished.connect(finished)
        args = ["-c", "from djpdf.scans2pdf import main; main()",
                os.path.abspath(url.toLocalFile())]
        if self._verbose:
            args.append("--verbose")
        p.start(sys.executable, args)
        p.write(json.dumps([p._data for p in self._pages]).encode())
        p.closeWriteChannel()
예제 #13
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # Hold process reference.
        self.p = None

        layout = QVBoxLayout()

        self.text = QPlainTextEdit()
        layout.addWidget(self.text)

        self.progress = QProgressBar()
        layout.addWidget(self.progress)

        btn_run = QPushButton("Execute")
        btn_run.clicked.connect(self.start)

        layout.addWidget(btn_run)

        w = QWidget()
        w.setLayout(layout)
        self.setCentralWidget(w)

        self.show()

    def start(self):
        if self.p is not None:
            return

        self.p = QProcess()
        self.p.readyReadStandardOutput.connect(self.handle_stdout)
        self.p.readyReadStandardError.connect(self.handle_stderr)
        self.p.stateChanged.connect(self.handle_state)
        self.p.finished.connect(self.cleanup)
        self.p.start("python", ["dummy_script.py"])

    def handle_stderr(self):
        result = bytes(self.p.readAllStandardError()).decode("utf8")
        progress = simple_percent_parser(result)

        self.progress.setValue(progress)

    def handle_stdout(self):
        result = bytes(self.p.readAllStandardOutput()).decode("utf8")
        data = extract_vars(result)

        self.text.appendPlainText(str(data))

    def handle_state(self, state):
        self.statusBar().showMessage(STATES[state])

    def cleanup(self):
        self.p = None
예제 #14
0
def start_guardian_detached():
    logging.info('starting guardian process')
    guardian_loc = 'C:\\Program Files (x86)\\PWUploader\\PWGuardian.exe'
    processes = (p.name() for p in psutil.process_iter())
    guardian_running = "PWGuardian.exe" in processes
    if not guardian_running:
        process = QProcess()
        res, pid = process.startDetached(guardian_loc, [""], "")
        if res == False:
            logging.error('Unable to start the guardian process. %s', UUID)
        else:
            logging.info(f'Started PWGuardian.exe, pid: {pid}')
예제 #15
0
class EmcExe_Qt(EmcExe):
    """ PySide2 implementation of the EmcExec """
    def __init__(self, *args, **kargs):
        super().__init__(*args, **kargs)

        self._proc = QProcess()
        self._proc.errorOccurred.connect(self._error_cb)

        if self._done_cb:
            self._proc.finished.connect(self._finished_cb)

        if self._grab_output:
            self._proc.readyReadStandardOutput.connect(self._stdout_cb)

        if self._params:
            self._proc.start(self._cmd, self._params)
        else:
            self._proc.start(self._cmd)

    def delete(self) -> None:
        super().delete()
        if self._proc and self._proc.state() == QProcess.Running:
            self._proc.kill()
        self._proc = None

    def _finished_cb(self, exit_code):
        self._call_user_callback(exit_code)

    def _error_cb(self, error):
        if self._proc and not self.deleted:
            self._call_user_callback(-1)

    def _stdout_cb(self):
        if self._proc and not self.deleted:
            self._out_buffer.append(self._proc.readAllStandardOutput().data())
예제 #16
0
 def __init__(self, parent: QWidget, **kwargs):
     self.cls_name = self.__class__.__name__
     self.parent = parent
     self.action = kwargs.get("action", Actions.DOWNLOAD)
     self.thread_pool = QThreadPool()
     self.check(**kwargs)
     self.div: AppDiv
     self.div_init()
     self.count = 0
     self.start_time = 0
     self.cancel = False
     self.process = QProcess(self.parent)
     self.process.readyReadStandardOutput.connect(self.on_readoutput)
     self.process.readyReadStandardError.connect(self.on_readerror)
예제 #17
0
    def init_nn_process(self, parent):
        process = QProcess(parent)
        process.started.connect(
            lambda: self.process_modal.startButton.setDisabled(True))
        process.finished.connect(self.finish_nn_segmentation)

        return process
예제 #18
0
 def execute(self):
     wrk_file_path = self.label.text()
     if wrk_file_path.endswith('nk'):
         if self.process is None:
             self.process = QProcess()
             self.process.readyReadStandardOutput.connect(
                 self.handle_stdout)
             self.process.readyReadStandardError.connect(self.handle_stderr)
             self.process.stateChanged.connect(self.handle_state)
             self.process.finished.connect(self.process_finished)
             self.process.start('"{}" -it {} {}'.format(
                 nuke_path, python_file, wrk_file_path))
     else:
         msgBox = QMessageBox()
         msgBox.setText("Please Drag a nuke file")
         msgBox.exec_()
예제 #19
0
    def __init__(self, *args, **kargs):
        super().__init__(*args, **kargs)

        self._proc = QProcess()
        self._proc.errorOccurred.connect(self._error_cb)

        if self._done_cb:
            self._proc.finished.connect(self._finished_cb)

        if self._grab_output:
            self._proc.readyReadStandardOutput.connect(self._stdout_cb)

        if self._params:
            self._proc.start(self._cmd, self._params)
        else:
            self._proc.start(self._cmd)
예제 #20
0
    def _start_session(self):
        if self._session is not None:
            return

        self._session = QProcess(self)
        self._session.finished.connect(self._session_ended)
        self._session.readyReadStandardOutput.connect(self._log_append_stdout)
        self._session.readyReadStandardError.connect(self._log_append_stderr)

        settings = QSettings()
        self._session.start(sys.executable, [
            'run_session.py',
            settings.value('CyKitAddress', app.DEFAULT_CYKIT_ADDRESS),
            str(settings.value('CyKitPort', app.DEFAULT_CYKIT_PORT)),
            str(self._interaction_server.port)
        ])
예제 #21
0
 def startVivado(self):
     self.operation = Operation.NONE
     TclInterfaceHandler.isOperationFinished = False
     XtclLog.writeLine(
         "================ Starting Vivado process ================ ",
         XtclCommon.blue)
     XtclLog.write("PLEASE WAIT UNTIL YOU SEE \"# vwait forever\" MESSAGE!",
                   XtclCommon.red)
     command = XtclSettings.vivadoDirectory + "/vivado.bat -nojournal -nolog -mode batch -source jtag_configuration_engine.tcl"
     # Create runner
     self.vivadoProcess = QProcess()
     self.vivadoProcess.readyReadStandardError.connect(self.errorInfo)
     self.vivadoProcess.readyReadStandardOutput.connect(
         self.readAllStandardOutput)
     self.vivadoProcess.finished.connect(self.finished)
     self.vivadoProcess.start(command)
     return
예제 #22
0
    def __init__(self, output_widget: QTextEdit = None):

        # create install process
        self._output_widget = None
        self.process = QProcess()
        self.process.setProgram(sys.executable)
        self.process.setProcessChannelMode(QProcess.MergedChannels)
        self.process.readyReadStandardOutput.connect(self._on_stdout_ready)
        # setup process path
        env = QProcessEnvironment()
        combined_paths = os.pathsep.join(
            [site.getsitepackages()[0], env.systemEnvironment().value("PYTHONPATH")]
        )
        env.insert("PATH", QProcessEnvironment.systemEnvironment().value("PATH"))
        env.insert("PYTHONPATH", combined_paths)
        self.process.setProcessEnvironment(env)
        self.set_output_widget(output_widget)
예제 #23
0
 def __init__(self, media, parent):
     super(VideoMediaView, self).__init__(media, parent)
     self.widget = QWidget(parent)
     self.process = QProcess(self._widget)
     self.process.setObjectName('%s-process' % self.objectName())
     self.std_out = []
     self.errors = []
     self.stopping = False
     self.mute = False
     self.widget.setGeometry(media['geometry'])
     self.connect(self.process, SIGNAL('error()'), self.process_error)
     self.connect(self.process, SIGNAL('finished()'), self.process_finished)
     self.connect(self.process, SIGNAL('started()'), self.process_started)
     self.set_default_widget_prop()
     self.stop_timer = QTimer(self)
     self.stop_timer.setSingleShot(True)
     self.stop_timer.setInterval(1000)
     self.stop_timer.timeout.connect(self.process_timeout)
예제 #24
0
 def install(self, path):
     """Installs the prgram using wine"""
     print("Installing: " + path)
     uri = urllib.parse.urlparse(path)
     qprocess = QProcess()
     qprocess.finished.connect(self.onFinished)
     qprocess.errorOccurred.connect(self.onErrorOccurred)
     qprocess.setProgram("wine")
     qprocess.setArguments(["".join(uri[1:])])
     # qprocess.start() # This Crashes
     qprocess.startDetached()  # This does not supports signals
예제 #25
0
class Example(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.setWindowTitle('QProcess')
        self.setGeometry(100, 100, 600, 300)
        self.show()

    def initUI(self):
        tool_run = QToolButton()
        tool_run.setText('Run')
        tool_run.clicked.connect(self.callProgram)

        toolbar = QToolBar()
        self.addToolBar(toolbar)
        toolbar.addWidget(tool_run)

        self.output = QTextEdit()
        self.setCentralWidget(self.output)

        # QProcess object for external app
        self.process = QProcess(self)
        # QProcess emits `readyRead` when there is data to be read
        self.process.readyRead.connect(self.dataReady)

        # Just to prevent accidentally running multiple times
        # Disable the button when process starts, and enable it when it finishes
        self.process.started.connect(lambda: tool_run.setEnabled(False))
        self.process.finished.connect(lambda: tool_run.setEnabled(True))

    def dataReady(self):
        cursor = self.output.textCursor()
        cursor.movePosition(cursor.End)
        content = self.process.readAllStandardOutput()
        cursor.insertText(str(content, 'utf-8'))
        self.output.ensureCursorVisible()

    def callProgram(self):
        # run the process
        # `start` takes the exec and a list of arguments
        if os.name == 'nt':
            self.process.start('ping', ['127.0.0.1'])
        else:
            self.process.start('ping', ['-c', '4', '127.0.0.1'])
예제 #26
0
def runProcess(command, arguments):
    process = QProcess()
    process.start(command, arguments)
    process.waitForFinished()
    result = []
    for line in str(process.readAllStandardOutput()).split(os.linesep):
        result.append(line)
    return result
예제 #27
0
    def testWithoutArgs(self):
        '''Connect QProcess.started() to QTimeLine.togglePaused()'''
        process = QProcess()
        timeline = QTimeLine()

        QObject.connect(process, SIGNAL('finished(int, QProcess::ExitStatus)'),
                        timeline, SLOT('toggleDirection()'))

        orig_dir = timeline.direction()

        process.start(sys.executable, ['-c', '"print 42"'])
        process.waitForFinished()

        new_dir = timeline.direction()

        if orig_dir == QTimeLine.Forward:
            self.assertEqual(new_dir, QTimeLine.Backward)
        else:
            self.assertEqual(new_dir, QTimeLine.Forward)
    def testQProcessFinished(self):
        '''Multiple connections to QProcess.finished(int)'''
        sender = QProcess()
        receivers = [BasicPySlotCase() for x in range(10)]

        def start_proc(*args):
            sender.start(sys.executable, ['-c', '""'])
            sender.waitForFinished()

        self.run_many(sender, 'finished(int)', start_proc, receivers, (0, ))
예제 #29
0
    def __init__(self, toolbox, program=None, args=None, silent=False):
        """Class constructor.

        Args:
            toolbox (ToolboxUI): Instance of Main UI class.
            program (str): Path to program to run in the subprocess (e.g. julia.exe)
            args (list): List of argument for the program (e.g. path to script file)
            silent (bool): Whether or not to emit toolbox msg signals
        """
        super().__init__()
        self._toolbox = toolbox
        self._program = program
        self._args = args
        self._silent = silent
        self.process_failed = False
        self.process_failed_to_start = False
        self._user_stopped = False
        self._process = QProcess(self)
        self.output = None
예제 #30
0
 def testWithArgs(self):
     '''Connecting a lambda to a signal with arguments'''
     proc = QProcess()
     dummy = Dummy()
     QObject.connect(proc, SIGNAL('finished(int)'),
                     lambda x: setattr(dummy, 'called', x))
     proc.start(sys.executable, ['-c', '""'])
     proc.waitForFinished()
     self.assertEqual(dummy.called, proc.exitCode())
    def __init__(self, logger, program=None, args=None, silent=False, semisilent=False):
        """Class constructor.

        Args:
            logger (LoggerInterface): a logger instance
            program (str): Path to program to run in the subprocess (e.g. julia.exe)
            args (list): List of argument for the program (e.g. path to script file)
            silent (bool): Whether or not to emit logger msg signals
        """
        super().__init__(logger)
        self._program = program
        self._args = args
        self._silent = silent  # Do not show Event Log nor Process Log messages
        self._semisilent = semisilent  # Do not show Event Log messages but show Process Log messages
        self.process_failed = False
        self.process_failed_to_start = False
        self._user_stopped = False
        self._process = QProcess(self)
        self.process_output = None  # stdout when running silent
        self.error_output = None  # stderr when running silent
예제 #32
0
    def on_firmware_update(self, filepath):
        if self.ser_port:
            self.proc = QProcess(self)
            self.proc.readyReadStandardOutput.connect(self.stdoutReady)
            self.proc.readyReadStandardError.connect(self.stderrReady)

            if sys.platform == "win32":
                command = f'{self.udr2} --program {self.ser_port.port} < {filepath}'
                self.usb_frame.out.write(
                    "Firmware update started, please wait ")
                # displays running dots on windows to pretend it is not stalled
                self.bullshitTimer = QTimer()
                self.bullshitTimer.timeout.connect(self.stdoutBullshit)
                self.bullshitTimer.start(1000)
                self.proc.setProcessChannelMode(QProcess.MergedChannels)
                self.proc.start('cmd.exe', ['/c', command])
            else:
                command = f'{self.udr2} --program {self.ser_port.port} < "{filepath}"'
                self.bullshitTimer = None
                self.proc.start('bash', ['-c', command])
예제 #33
0
 def create_env(self, py_, vir_path, name):
     self.infobox = ProgressMsgDialog(msg="准备中...")
     self.infobox.show()
     self.infobox.raise_()
     self.infobox_flag = False
     self.p = QProcess()
     self.p.readyReadStandardOutput.connect(self.readout_slot)
     self.p.finished.connect(self.finished_slot)
     virtualenv_ = "virtualenv"
     img_ = G.config.get_pypi_source()
     cmd = " ".join([py_, "-m", 'pip', 'install', virtualenv_] + img_)
     self.p.start(cmd)
     self.p.waitForFinished()
     # 开始新建venv
     self.infobox.sig.msg.emit('新建虚拟环境中...')
     cmd = " ".join([py_, "-m", virtualenv_, "--no-site-packages", vir_path])
     self.p.start(cmd)
     self.infobox_flag = True
     # record
     py_path = join_path(vir_path, 'Scripts', 'python.exe')
     G.config.python_path.update({name: py_path})
예제 #34
0
 def testWithArgs(self):
     '''Connecting a lambda to a signal with arguments'''
     proc = QProcess()
     dummy = Dummy()
     QObject.connect(proc, SIGNAL('finished(int)'),
                     lambda x: setattr(dummy, 'called', x))
     proc.start(sys.executable, ['-c', '""'])
     proc.waitForFinished()
     self.assertEqual(dummy.called, proc.exitCode())
예제 #35
0
def runProcess(command, arguments):
    process = QProcess()
    process.start(command, arguments)
    process.waitForFinished()
    std_output = process.readAllStandardOutput().data().decode('utf-8')
    return std_output.split('\n')