• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python QtCore.QProcess类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中qtpy.QtCore.QProcess的典型用法代码示例。如果您正苦于以下问题:Python QProcess类的具体用法?Python QProcess怎么用?Python QProcess使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了QProcess类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: update_environment

    def update_environment(self, filename, name=None, prefix=None, emit=False):
        """
        Set environment at 'prefix' or 'name' to match 'filename' spec as yaml.
        """
        if name and prefix:
            raise TypeError("Exactly one of 'name' or 'prefix' is required.")

        if self._is_not_running:
            if name:
                temporal_envname = name

            if prefix:
                temporal_envname = 'tempenv' + int(random.random()*10000000)
                envs_dir = self.info()['envs_dirs'][0]
                os.symlink(prefix, os.sep.join([envs_dir, temporal_envname]))

            cmd = self._abspath(True)
            cmd.extend(['env', 'update', '--name', temporal_envname, '--file',
                        os.path.abspath(filename)])
            qprocess = QProcess()
            qprocess.start(cmd[0], cmd[1:])
            qprocess.waitForFinished()

            if prefix:
                os.unlink(os.sep.join([envs_dir, 'tempenv']))
开发者ID:ccordoba12,项目名称:conda-manager,代码行数:25,代码来源:conda_api_q.py


示例2: __init__

    def __init__(self, cmd_list, environ=None):
        """
        Process worker based on a QProcess for non blocking UI.

        Parameters
        ----------
        cmd_list : list of str
            Command line arguments to execute.
        environ : dict
            Process environment,
        """
        super(ProcessWorker, self).__init__()
        self._result = None
        self._cmd_list = cmd_list
        self._fired = False
        self._communicate_first = False
        self._partial_stdout = None
        self._started = False

        self._timer = QTimer()
        self._process = QProcess()
        self._set_environment(environ)

        self._timer.setInterval(150)
        self._timer.timeout.connect(self._communicate)
        self._process.readyReadStandardOutput.connect(self._partial)
开发者ID:0xBADCA7,项目名称:spyder,代码行数:26,代码来源:workers.py


示例3: start

 def start(self):
     filename = to_text_string(self.filecombo.currentText())
     
     self.process = QProcess(self)
     self.process.setProcessChannelMode(QProcess.SeparateChannels)
     self.process.setWorkingDirectory(osp.dirname(filename))
     self.process.readyReadStandardOutput.connect(self.read_output)
     self.process.readyReadStandardError.connect(
                                       lambda: self.read_output(error=True))
     self.process.finished.connect(lambda ec, es=QProcess.ExitStatus:
                                   self.finished(ec, es))
     self.stop_button.clicked.connect(self.process.kill)
     
     self.output = ''
     self.error_output = ''
     
     plver = PYLINT_VER
     if plver is not None:
         if plver.split('.')[0] == '0':
             p_args = ['-i', 'yes']
         else:
             # Option '-i' (alias for '--include-ids') was removed in pylint
             # 1.0
             p_args = ["--msg-template='{msg_id}:{line:3d},"\
                       "{column}: {obj}: {msg}"]
         p_args += [osp.basename(filename)]
     else:
         p_args = [osp.basename(filename)]
     self.process.start(PYLINT_PATH, p_args)
     
     running = self.process.waitForStarted()
     self.set_running_state(running)
     if not running:
         QMessageBox.critical(self, _("Error"),
                              _("Process failed to start"))
开发者ID:ShenggaoZhu,项目名称:spyder,代码行数:35,代码来源:pylintgui.py


示例4: start

    def start(self, wdir=None, args=None, pythonpath=None):
        filename = to_text_string(self.filecombo.currentText())
        if wdir is None:
            wdir = self._last_wdir
            if wdir is None:
                wdir = osp.basename(filename)
        print(filename)
        if os.name == 'nt':
            # On Windows, one has to replace backslashes by slashes to avoid
            # confusion with escape characters (otherwise, for example, '\t'
            # will be interpreted as a tabulation):
            filename = osp.normpath(filename).replace(os.sep, '/')
        if args is None:
            args = self._last_args
            if args is None:
                args = []
        if pythonpath is None:
            pythonpath = self._last_pythonpath
        self._last_wdir = wdir
        self._last_args = args
        self._last_pythonpath = pythonpath

        self.datelabel.setText(_('Running tests, please wait...'))

        self.process = QProcess(self)
        self.process.setProcessChannelMode(QProcess.SeparateChannels)
        self.process.setWorkingDirectory(filename)
        self.process.readyReadStandardOutput.connect(self.read_output)
        self.process.readyReadStandardError.connect(
            lambda: self.read_output(error=True))
        self.process.finished.connect(self.finished)
        self.stop_button.clicked.connect(self.process.kill)

        if pythonpath is not None:
            env = [to_text_string(_pth)
                   for _pth in self.process.systemEnvironment()]
            baseshell.add_pathlist_to_PYTHONPATH(env, pythonpath)
            self.process.setEnvironment(env)

        self.output = ''
        self.error_output = ''

        executable = "py.test"
        p_args = ['--junit-xml', self.DATAPATH]

#        executable = "nosetests"
#        p_args = ['--with-xunit', "--xunit-file=%s" % self.DATAPATH]

        if args:
            p_args.extend(programs.shell_split(args))
        self.process.start(executable, p_args)

        running = self.process.waitForStarted()
        self.set_running_state(running)
        if not running:
            QMessageBox.critical(self, _("Error"),
                                 _("Process failed to start"))
开发者ID:spyder-ide,项目名称:spyder.unittest,代码行数:57,代码来源:unittestinggui.py


示例5: create_process

    def create_process(self):
        self.shell.clear()

        self.process = QProcess(self)
        self.process.setProcessChannelMode(QProcess.MergedChannels)

        # PYTHONPATH (in case we use Python in this terminal, e.g. py2exe)
        env = [to_text_string(_path)
               for _path in self.process.systemEnvironment()]

        processEnvironment = QProcessEnvironment()
        for envItem in env:
            envName, separator, envValue = envItem.partition('=')
            processEnvironment.insert(envName, envValue)

        add_pathlist_to_PYTHONPATH(env, self.path)
        self.process.setProcessEnvironment(processEnvironment)                   

        
        # Working directory
        if self.wdir is not None:
            self.process.setWorkingDirectory(self.wdir)
            
        # Shell arguments
        if os.name == 'nt':
            p_args = ['/Q']
        else:
            p_args = ['-i']
            
        if self.arguments:
            p_args.extend( shell_split(self.arguments) )
        
        self.process.readyReadStandardOutput.connect(self.write_output)
        self.process.finished.connect(self.finished)
        self.kill_button.clicked.connect(self.process.kill)
        
        if os.name == 'nt':
            self.process.start('cmd.exe', p_args)
        else:
            # Using bash:
            self.process.start('bash', p_args)
            self.send_to_process('PS1="\\[email protected]\\h:\\w> "\n')
            
        running = self.process.waitForStarted()
        self.set_running_state(running)
        if not running:
            QMessageBox.critical(self, _("Error"),
                                 _("Process failed to start"))
        else:
            self.shell.setFocus()
            self.started.emit()
            
        return self.process
开发者ID:ChunHungLiu,项目名称:spyder,代码行数:53,代码来源:systemshell.py


示例6: environment_exists

    def environment_exists(self, name=None, prefix=None, abspath=True,
                           emit=False):
        """
        Check if an environment exists by 'name' or by 'prefix'. If query is
        by 'name' only the default conda environments directory is searched.
        """
        if name and prefix:
            raise TypeError("Exactly one of 'name' or 'prefix' is required.")

        qprocess = QProcess()
        cmd_list = self._abspath(abspath)
        cmd_list.extend(['list', '--json'])

        if name:
            cmd_list.extend(['--name', name])
        else:
            cmd_list.extend(['--prefix', prefix])

        qprocess.start(cmd_list[0], cmd_list[1:])
        qprocess.waitForFinished()
        output = qprocess.readAllStandardOutput()
        output = handle_qbytearray(output, CondaProcess.ENCODING)
        info = json.loads(output)

        if emit:
            self.sig_finished.emit("info", unicode(info), "")

        return 'error' not in info
开发者ID:ccordoba12,项目名称:conda-manager,代码行数:28,代码来源:conda_api_q.py


示例7: pip_list

    def pip_list(self, name=None, prefix=None, abspath=True, emit=False):
        """
        Get list of pip installed packages.
        """
        if (name and prefix) or not (name or prefix):
            raise TypeError("conda pip: exactly one of 'name' ""or 'prefix' "
                            "required.")

        if self._is_not_running:
            cmd_list = self._abspath(abspath)
            if name:
                cmd_list.extend(['list', '--name', name])
            if prefix:
                cmd_list.extend(['list', '--prefix', prefix])

            qprocess = QProcess()
            qprocess.start(cmd_list[0], cmd_list[1:])
            qprocess.waitForFinished()
            output = qprocess.readAllStandardOutput()
            output = handle_qbytearray(output, CondaProcess.ENCODING)

            result = []
            lines = output.split('\n')

            for line in lines:
                if '<pip>' in line:
                    temp = line.split()[:-1] + ['pip']
                    result.append('-'.join(temp))

            if emit:
                self.sig_finished.emit("pip", str(result), "")

        return result
开发者ID:ccordoba12,项目名称:conda-manager,代码行数:33,代码来源:conda_api_q.py


示例8: __init__

    def __init__(self, parent):
        QObject.__init__(self, parent)
        self._parent = parent
        self._output = None
        self._partial = None
        self._stdout = None
        self._error = None
        self._parse = False
        self._function_called = ""
        self._name = None
        self._process = QProcess()
        self.set_root_prefix()

        # Signals
        self._process.finished.connect(self._call_conda_ready)
        self._process.readyReadStandardOutput.connect(self._call_conda_partial)
开发者ID:spyder-ide,项目名称:conda-api-q,代码行数:16,代码来源:conda_api_q.py


示例9: run

    def run(self):
        """Handle the connection with the server.
        """
        # Set up the zmq port.
        self.socket = self.context.socket(zmq.PAIR)
        self.port = self.socket.bind_to_random_port('tcp://*')

        # Set up the process.
        self.process = QProcess(self)
        if self.cwd:
            self.process.setWorkingDirectory(self.cwd)
        p_args = ['-u', self.target, str(self.port)]
        if self.extra_args is not None:
            p_args += self.extra_args

        # Set up environment variables.
        processEnvironment = QProcessEnvironment()
        env = self.process.systemEnvironment()
        if (self.env and 'PYTHONPATH' not in self.env) or DEV:
            python_path = osp.dirname(get_module_path('spyderlib'))
            # Add the libs to the python path.
            for lib in self.libs:
                try:
                    path = osp.dirname(imp.find_module(lib)[1])
                    python_path = osp.pathsep.join([python_path, path])
                except ImportError:
                    pass
            env.append("PYTHONPATH=%s" % python_path)
        if self.env:
            env.update(self.env)
        for envItem in env:
            envName, separator, envValue = envItem.partition('=')
            processEnvironment.insert(envName, envValue)
        self.process.setProcessEnvironment(processEnvironment)

        # Start the process and wait for started.
        self.process.start(self.executable, p_args)
        self.process.finished.connect(self._on_finished)
        running = self.process.waitForStarted()
        if not running:
            raise IOError('Could not start %s' % self)

        # Set up the socket notifer.
        fid = self.socket.getsockopt(zmq.FD)
        self.notifier = QSocketNotifier(fid, QSocketNotifier.Read, self)
        self.notifier.activated.connect(self._on_msg_received)
开发者ID:OverKast,项目名称:spyder,代码行数:46,代码来源:plugin_client.py


示例10: _prepare_process

    def _prepare_process(self, config, pythonpath):
        """
        Prepare and return process for running the unit test suite.

        This sets the working directory and environment.
        """
        process = QProcess(self)
        process.setProcessChannelMode(QProcess.MergedChannels)
        process.setWorkingDirectory(config.wdir)
        process.finished.connect(self.finished)
        if pythonpath is not None:
            env = [
                to_text_string(_pth)
                for _pth in process.systemEnvironment()
            ]
            add_pathlist_to_PYTHONPATH(env, pythonpath)
            processEnvironment = QProcessEnvironment()
            for envItem in env:
                envName, separator, envValue = envItem.partition('=')
                processEnvironment.insert(envName, envValue)
            process.setProcessEnvironment(processEnvironment)
        return process
开发者ID:jitseniesen,项目名称:spyder.unittest,代码行数:22,代码来源:runnerbase.py


示例11: __init__

    def __init__(self, parent, on_finished=None, on_partial=None):
        QObject.__init__(self, parent)
        self._parent = parent
        self.output = None
        self.partial = None
        self.stdout = None
        self.error = None
        self._parse = False
        self._function_called = ''
        self._name = None
        self._process = QProcess()
        self._on_finished = on_finished

        self._process.finished.connect(self._call_conda_ready)
        self._process.readyReadStandardOutput.connect(self._call_conda_partial)

        if on_finished is not None:
            self._process.finished.connect(on_finished)
        if on_partial is not None:
            self._process.readyReadStandardOutput.connect(on_partial)

        self.set_root_prefix()
开发者ID:lzfernandes,项目名称:conda-manager,代码行数:22,代码来源:conda_api_q.py


示例12: __init__

    def __init__(self, cmd_list, parse=False, pip=False, callback=None,
                 extra_kwargs={}):
        super(ProcessWorker, self).__init__()
        self._result = None
        self._cmd_list = cmd_list
        self._parse = parse
        self._pip = pip
        self._conda = not pip
        self._callback = callback
        self._fired = False
        self._communicate_first = False
        self._partial_stdout = None
        self._extra_kwargs = extra_kwargs

        self._timer = QTimer()
        self._process = QProcess()

        self._timer.setInterval(50)

        self._timer.timeout.connect(self._communicate)
        self._process.finished.connect(self._communicate)
        self._process.readyReadStandardOutput.connect(self._partial)
开发者ID:martindurant,项目名称:conda-manager,代码行数:22,代码来源:conda_api.py


示例13: info

    def info(self, abspath=True):
        """
        Return a dictionary with configuration information.
        No guarantee is made about which keys exist.  Therefore this function
        should only be used for testing and debugging.
        """
#        return self._call_and_parse(['info', '--json'], abspath=abspath)

        qprocess = QProcess()
        cmd_list = self._abspath(abspath)
        cmd_list.extend(['info', '--json'])
        qprocess.start(cmd_list[0], cmd_list[1:])
        qprocess.waitForFinished()
        output = qprocess.readAllStandardOutput()
        output = handle_qbytearray(output, CondaProcess.ENCODING)
        info = json.loads(output)
        return info
开发者ID:lzfernandes,项目名称:conda-manager,代码行数:17,代码来源:conda_api_q.py


示例14: __init__

    def __init__(self, cmd_list, parse=False, pip=False, callback=None,
                 extra_kwargs=None):
        """Conda worker based on a QProcess for non blocking UI.

        Parameters
        ----------
        cmd_list : list of str
            Command line arguments to execute.
        parse : bool (optional)
            Parse json from output.
        pip : bool (optional)
            Define as a pip command.
        callback : func (optional)
            If the process has a callback to process output from comd_list.
        extra_kwargs : dict
            Arguments for the callback.
        """
        super(ProcessWorker, self).__init__()
        self._result = None
        self._cmd_list = cmd_list
        self._parse = parse
        self._pip = pip
        self._conda = not pip
        self._callback = callback
        self._fired = False
        self._communicate_first = False
        self._partial_stdout = None
        self._extra_kwargs = extra_kwargs if extra_kwargs else {}

        self._timer = QTimer()
        self._process = QProcess()

        self._timer.setInterval(150)

        self._timer.timeout.connect(self._communicate)
        # self._process.finished.connect(self._communicate)
        self._process.readyReadStandardOutput.connect(self._partial)
开发者ID:gitter-badger,项目名称:conda-manager,代码行数:37,代码来源:conda_api.py


示例15: info

    def info(self, abspath=True):
        """
        Return a dictionary with configuration information.

        No guarantee is made about which keys exist.  Therefore this function
        should only be used for testing and debugging.
        """
        if self._is_not_running():
            qprocess = QProcess()
            cmd_list = self._abspath(abspath)
            cmd_list.extend(["info", "--json"])
            qprocess.start(cmd_list[0], cmd_list[1:])
            qprocess.waitForFinished()
            output = qprocess.readAllStandardOutput()
            output = handle_qbytearray(output, CondaProcess.ENCODING)
            info = json.loads(output)

            self.sig_finished.emit("info", str(info), "")
            return info
开发者ID:spyder-ide,项目名称:conda-api-q,代码行数:19,代码来源:conda_api_q.py


示例16: ProcessWorker

class ProcessWorker(QObject):
    """
    """
    sig_finished = Signal(object, object, object)
    sig_partial = Signal(object, object, object)

    def __init__(self, cmd_list, parse=False, pip=False, callback=None,
                 extra_kwargs={}):
        super(ProcessWorker, self).__init__()
        self._result = None
        self._cmd_list = cmd_list
        self._parse = parse
        self._pip = pip
        self._conda = not pip
        self._callback = callback
        self._fired = False
        self._communicate_first = False
        self._partial_stdout = None
        self._extra_kwargs = extra_kwargs

        self._timer = QTimer()
        self._process = QProcess()

        self._timer.setInterval(50)

        self._timer.timeout.connect(self._communicate)
        self._process.finished.connect(self._communicate)
        self._process.readyReadStandardOutput.connect(self._partial)

    def _partial(self):
        raw_stdout = self._process.readAllStandardOutput()
        stdout = handle_qbytearray(raw_stdout, _CondaAPI.UTF8)

        json_stdout = stdout.replace('\n\x00', '')
        try:
            json_stdout = json.loads(json_stdout)
        except Exception:
            json_stdout = stdout

        if self._partial_stdout is None:
            self._partial_stdout = stdout
        else:
            self._partial_stdout += stdout

        self.sig_partial.emit(self, json_stdout, None)

    def _communicate(self):
        """
        """
        if not self._communicate_first:
            if self._process.state() == QProcess.NotRunning:
                self.communicate()
        elif self._fired:
            self._timer.stop()

    def communicate(self):
        """
        """
        self._communicate_first = True
        self._process.waitForFinished()

        if self._partial_stdout is None:
            raw_stdout = self._process.readAllStandardOutput()
            stdout = handle_qbytearray(raw_stdout, _CondaAPI.UTF8)
        else:
            stdout = self._partial_stdout

        raw_stderr = self._process.readAllStandardError()
        stderr = handle_qbytearray(raw_stderr, _CondaAPI.UTF8)
        result = [stdout.encode(_CondaAPI.UTF8), stderr.encode(_CondaAPI.UTF8)]

        # FIXME: Why does anaconda client print to stderr???
        if PY2:
            stderr = stderr.decode()
        if 'using anaconda cloud api site' not in stderr.lower():
            if stderr.strip() and self._conda:
                raise Exception('{0}:\n'
                                'STDERR:\n{1}\nEND'
                                ''.format(' '.join(self._cmd_list),
                                          stderr))
#            elif stderr.strip() and self._pip:
#                raise PipError(self._cmd_list)
        else:
            result[-1] = ''

        if self._parse and stdout:
            try:
                result = json.loads(stdout), result[-1]
            except ValueError as error:
                result = stdout, error

            if 'error' in result[0]:
                error = '{0}: {1}'.format(" ".join(self._cmd_list),
                                          result[0]['error'])
                result = result[0], error

        if self._callback:
            result = self._callback(result[0], result[-1],
                                    **self._extra_kwargs), result[-1]

#.........这里部分代码省略.........
开发者ID:martindurant,项目名称:conda-manager,代码行数:101,代码来源:conda_api.py


示例17: CondaProcess

class CondaProcess(QObject):
    """conda-api modified to work with QProcess instead of popen"""
    ENCODING = 'ascii'

    def __init__(self, parent, on_finished=None, on_partial=None):
        QObject.__init__(self, parent)
        self._parent = parent
        self.output = None
        self.partial = None
        self.stdout = None
        self.error = None
        self._parse = False
        self._function_called = ''
        self._name = None
        self._process = QProcess()
        self._on_finished = on_finished

        self._process.finished.connect(self._call_conda_ready)
        self._process.readyReadStandardOutput.connect(self._call_conda_partial)

        if on_finished is not None:
            self._process.finished.connect(on_finished)
        if on_partial is not None:
            self._process.readyReadStandardOutput.connect(on_partial)

        self.set_root_prefix()

    def _call_conda_partial(self):
        """ """
        stdout = self._process.readAllStandardOutput()
        stdout = handle_qbytearray(stdout, CondaProcess.ENCODING)

        stderr = self._process.readAllStandardError()
        stderr = handle_qbytearray(stderr, CondaProcess.ENCODING)

        if self._parse:
            self.output = json.loads(stdout)
        else:
            self.output = stdout

        self.partial = self.output
        self.stdout = self.output
        self.error = stderr

#        print(self.partial)
#        print(self.error)

    def _call_conda_ready(self):
        """function called when QProcess in _call_conda finishes task"""
        function = self._function_called

        if self.stdout is None:
            stdout = to_text_string(self._process.readAllStandardOutput(),
                                    encoding=CondaProcess.ENCODING)
        else:
            stdout = self.stdout

        if self.error is None:
            stderr = to_text_string(self._process.readAllStandardError(),
                                    encoding=CondaProcess.ENCODING)
        else:
            stderr = self.error

        if function == 'get_conda_version':
            pat = re.compile(r'conda:?\s+(\d+\.\d\S+|unknown)')
            m = pat.match(stderr.strip())
            if m is None:
                m = pat.match(stdout.strip())
            if m is None:
                raise Exception('output did not match: %r' % stderr)
            self.output = m.group(1)
#        elif function == 'get_envs':
#            info = self.output
#            self.output = info['envs']
#        elif function == 'get_prefix_envname':
#            name = self._name
#            envs = self.output
#            self.output = self._get_prefix_envname_helper(name, envs)
#            self._name = None
        elif function == 'config_path':
            result = self.output
            self.output = result['rc_path']
        elif function == 'config_get':
            result = self.output
            self.output = result['get']
        elif (function == 'config_delete' or function == 'config_add' or
                function == 'config_set' or function == 'config_remove'):
            result = self.output
            self.output = result.get('warnings', [])
        elif function == 'pip':
            result = []
            lines = self.output.split('\n')
            for line in lines:
                if '<pip>' in line:
                    temp = line.split()[:-1] + ['pip']
                    result.append('-'.join(temp))
            self.output = result

        if stderr.strip():
            self.error = stderr
#.........这里部分代码省略.........
开发者ID:lzfernandes,项目名称:conda-manager,代码行数:101,代码来源:conda_api_q.py


示例18: ExternalSystemShell

class ExternalSystemShell(ExternalShellBase):
    """External Shell widget: execute Python script in a separate process"""
    SHELL_CLASS = TerminalWidget
    started = Signal()
    
    def __init__(self, parent=None, wdir=None, path=[], light_background=True,
                 menu_actions=None, show_buttons_inside=True,
                 show_elapsed_time=True):
        ExternalShellBase.__init__(self, parent=parent, fname=None, wdir=wdir,
                                   history_filename='.history',
                                   light_background=light_background,
                                   menu_actions=menu_actions,
                                   show_buttons_inside=show_buttons_inside,
                                   show_elapsed_time=show_elapsed_time)
        
        # Additional python path list
        self.path = path
        
        # For compatibility with the other shells that can live in the external
        # console
        self.is_ipykernel = False
        self.connection_file = None

    def get_icon(self):
        return ima.icon('cmdprompt')

    def finish_process(self):
        while not self.process.waitForFinished(100):
            self.process.kill();

    def create_process(self):
        self.shell.clear()

        self.process = QProcess(self)
        self.process.setProcessChannelMode(QProcess.MergedChannels)

        # PYTHONPATH (in case we use Python in this terminal, e.g. py2exe)
        env = [to_text_string(_path)
               for _path in self.process.systemEnvironment()]

        processEnvironment = QProcessEnvironment()
        for envItem in env:
            envName, separator, envValue = envItem.partition('=')
            processEnvironment.insert(envName, envValue)

        add_pathlist_to_PYTHONPATH(env, self.path)
        self.process.setProcessEnvironment(processEnvironment)                   

        
        # Working directory
        if self.wdir is not None:
            self.process.setWorkingDirectory(self.wdir)
            
        # Shell arguments
        if os.name == 'nt':
            p_args = ['/Q']
        else:
            p_args = ['-i']
            
        if self.arguments:
            p_args.extend( shell_split(self.arguments) )
        
        self.process.readyReadStandardOutput.connect(self.write_output)
        self.process.finished.connect(self.finished)
        self.kill_button.clicked.connect(self.process.kill)
        
        if os.name == 'nt':
            self.process.start('cmd.exe', p_args)
        else:
            # Using bash:
            self.process.start('bash', p_args)
            self.send_to_process('PS1="\\[email protected]\\h:\\w> "\n')
            
        running = self.process.waitForStarted()
        self.set_running_state(running)
        if not running:
            QMessageBox.critical(self, _("Error"),
                                 _("Process failed to start"))
        else:
            self.shell.setFocus()
            self.started.emit()
            
        return self.process
    
#===============================================================================
#    Input/Output
#===============================================================================
    def transcode(self, qba):
        if os.name == 'nt':
            return to_text_string( CP850_CODEC.toUnicode(qba.data()) )
        else:
            return ExternalShellBase.transcode(self, qba)
    
    def send_to_process(self, text):
        if not is_text_string(text):
            text = to_text_string(text)
        if text[:-1] in ["clear", "cls", "CLS"]:
            self.shell.clear()
            self.send_to_process(os.linesep)
            return
#.........这里部分代码省略.........
开发者ID:ChunHungLiu,项目名称:spyder,代码行数:101,代码来源:systemshell.py


示例19: CondaProcess

class CondaProcess(QObject):
    """Conda API modified to work with QProcess instead of popen."""

    # Signals
    sig_finished = Signal(str, object, str)
    sig_partial = Signal(str, object, str)
    sig_started = Signal()

    ENCODING = "ascii"
    ROOT_PREFIX = None

    def __init__(self, parent):
        QObject.__init__(self, parent)
        self._parent = parent
        self._output = None
        self._partial = None
        self._stdout = None
        self._error = None
        self._parse = False
        self._function_called = ""
        self._name = None
        self._process = QProcess()
        self.set_root_prefix()

        # Signals
        self._process.finished.connect(self._call_conda_ready)
        self._process.readyReadStandardOutput.connect(self._call_conda_partial)

    # --- Helpers
    # -------------------------------------------------------------------------
    def _is_running(self):
        return self._process.state() != QProcess.NotRunning

    def _is_not_running(self):
        return self._process.state() == QProcess.NotRunning

    def _call_conda_partial(self):
        """ """
        stdout = self._process.readAllStandardOutput()
        stdout = handle_qbytearray(stdout, CondaProcess.ENCODING)

        stderr = self._process.readAllStandardError()
        stderr = handle_qbytearray(stderr, CondaProcess.ENCODING)

        if self._parse:
            try:
                self._output = json.loads(stdout)
            except Exception:
                # Result is a partial json. Can only be parsed when finished
                self._output = stdout
        else:
            self._output = stdout

        self._partial = self._output
        self._stdout = self._output
        self._error = stderr

        self.sig_partial.emit(self._function_called, self._partial, self._error)

    def _call_conda_ready(self):
        """Function called when QProcess in _call_conda finishes task."""
        function = self._function_called

        if self._stdout is None:
            stdout = to_text_string(self._process.readAllStandardOutput(), encoding=CondaProcess.ENCODING)
        else:
            stdout = self._stdout

        if self._error is None:
            stderr = to_text_string(self._process.readAllStandardError(), encoding=CondaProcess.ENCODING)
        else:
            stderr = self._error

        if function == "get_conda_version":
            pat = re.compile(r"conda:?\s+(\d+\.\d\S+|unknown)")
            m = pat.match(stderr.strip())
            if m is None:
                m = pat.match(stdout.strip())
            if m is None:
                raise Exception("output did not match: {0}".format(stderr))
            self._output = m.group(1)
        elif function == "config_path":
            result = self._output
            self._output = result["rc_path"]
        elif function == "config_get":
            result = self._output
            self._output = result["get"]
        elif (
            function == "config_delete"
            or function == "config_add"
            or function == "config_set"
            or function == "config_remove"
        ):
            result = self._output
            self._output = result.get("warnings", [])
        elif function == "pip":
            result = []
            lines = self._output.split("\n")
            for line in lines:
                if "<pip>" in line:
#.........这里部分代码省略.........
开发者ID:spyder-ide,项目名称:conda-api-q,代码行数:101,代码来源:conda_api_q.py


示例20: ExternalPythonShell


#.........这里部分代码省略.........
            else:
                argstr = _("No argument")
        else:
            argstr = _("Arguments...")
        self.args_action.setText(argstr)
        self.terminate_button.setVisible(not self.is_interpreter and state)
        if not state:
            self.toggle_globals_explorer(False)
        for btn in (self.cwd_button, self.env_button, self.syspath_button):
            btn.setEnabled(state and self.monitor_enabled)
        if self.namespacebrowser_button is not None:
            self.namespacebrowser_button.setEnabled(state)
    
    def set_namespacebrowser(self, namespacebrowser):
        """
        Set namespace browser *widget*
        Note: this method is not used in stand alone mode
        """
        self.namespacebrowser = namespacebrowser
        self.configure_namespacebrowser()
        
    def configure_namespacebrowser(self):
        """Connect the namespace browser to the notification thread"""
        if self.notification_thread is not None:
            self.notification_thread.refresh_namespace_browser.connect(
                         self.namespacebrowser.refresh_table)
            signal = self.notification_thread.sig_process_remote_view
            signal.connect(lambda data:
                           self.namespacebrowser.process_remote_view(data))
    
    def create_process(self):
        self.shell.clear()
            
        self.process = QProcess(self)
        if self.merge_output_channels:
            self.process.setProcessChannelMode(QProcess.MergedChannels)
        else:
            self.process.setProcessChannelMode(QProcess.SeparateChannels)
        self.shell.wait_for_ready_read.connect(
                     lambda: self.process.waitForReadyRead(250))
        
        # Working directory
        if self.wdir is not None:
            self.process.setWorkingDirectory(self.wdir)

        #-------------------------Python specific------------------------------
        # Python arguments
        p_args = ['-u']
        if DEBUG >= 3:
            p_args += ['-v']
        p_args += get_python_args(self.fname, self.python_args,
                                  self.interact_action.isChecked(),
                                  self.debug_action.isChecked(),
                                  self.arguments)
        
        env = [to_text_string(_path)
               for _path in self.process.systemEnvironment()]
        if self.pythonstartup:
            env.append('PYTHONSTARTUP=%s' % self.pythonstartup)
        
        #-------------------------Python specific-------------------------------
        # Post mortem debugging
        if self.post_mortem_action.isChecked():
            env.append('SPYDER_EXCEPTHOOK=True')

        # Set standard input/output encoding for Python consoles
开发者ID:ChunHungLiu,项目名称:spyder,代码行数:67,代码来源:pythonshell.py



注:本文中的qtpy.QtCore.QProcess类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python QtCore.QTimer类代码示例发布时间:2022-05-26
下一篇:
Python QtCore.QObject类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap