本文整理汇总了Python中qtpy.QtCore.QProcess.waitForFinished方法的典型用法代码示例。如果您正苦于以下问题:Python QProcess.waitForFinished方法的具体用法?Python QProcess.waitForFinished怎么用?Python QProcess.waitForFinished使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类qtpy.QtCore.QProcess
的用法示例。
在下文中一共展示了QProcess.waitForFinished方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: pip_list
# 需要导入模块: from qtpy.QtCore import QProcess [as 别名]
# 或者: from qtpy.QtCore.QProcess import waitForFinished [as 别名]
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
示例2: environment_exists
# 需要导入模块: from qtpy.QtCore import QProcess [as 别名]
# 或者: from qtpy.QtCore.QProcess import waitForFinished [as 别名]
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
示例3: update_environment
# 需要导入模块: from qtpy.QtCore import QProcess [as 别名]
# 或者: from qtpy.QtCore.QProcess import waitForFinished [as 别名]
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']))
示例4: info
# 需要导入模块: from qtpy.QtCore import QProcess [as 别名]
# 或者: from qtpy.QtCore.QProcess import waitForFinished [as 别名]
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
示例5: info
# 需要导入模块: from qtpy.QtCore import QProcess [as 别名]
# 或者: from qtpy.QtCore.QProcess import waitForFinished [as 别名]
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
示例6: PylintWidget
# 需要导入模块: from qtpy.QtCore import QProcess [as 别名]
# 或者: from qtpy.QtCore.QProcess import waitForFinished [as 别名]
#.........这里部分代码省略.........
module = '' # Should not be needed - just in case something goes wrong
for line in self.output.splitlines():
if line.startswith(txt_module):
# New module
module = line[len(txt_module):]
continue
# Supporting option include-ids: ('R3873:' instead of 'R:')
if not re.match('^[CRWE]+([0-9]{4})?:', line):
continue
i1 = line.find(':')
if i1 == -1:
continue
msg_id = line[:i1]
i2 = line.find(':', i1+1)
if i2 == -1:
continue
line_nb = line[i1+1:i2].strip()
if not line_nb:
continue
line_nb = int(line_nb.split(',')[0])
message = line[i2+1:]
item = (module, line_nb, message, msg_id)
results[line[0]+':'].append(item)
# Rate
rate = None
txt_rate = 'Your code has been rated at '
i_rate = self.output.find(txt_rate)
if i_rate > 0:
i_rate_end = self.output.find('/10', i_rate)
if i_rate_end > 0:
rate = self.output[i_rate+len(txt_rate):i_rate_end]
# Previous run
previous = ''
if rate is not None:
txt_prun = 'previous run: '
i_prun = self.output.find(txt_prun, i_rate_end)
if i_prun > 0:
i_prun_end = self.output.find('/10', i_prun)
previous = self.output[i_prun+len(txt_prun):i_prun_end]
filename = to_text_string(self.filecombo.currentText())
self.set_data(filename, (time.localtime(), rate, previous, results))
self.output = self.error_output + self.output
self.show_data(justanalyzed=True)
def kill_if_running(self):
if self.process is not None:
if self.process.state() == QProcess.Running:
self.process.kill()
self.process.waitForFinished()
def show_data(self, justanalyzed=False):
if not justanalyzed:
self.output = None
self.log_button.setEnabled(self.output is not None \
and len(self.output) > 0)
self.kill_if_running()
filename = to_text_string(self.filecombo.currentText())
if not filename:
return
_index, data = self.get_data(filename)
if data is None:
text = _('Source code has not been rated yet.')
self.treewidget.clear_results()
date_text = ''
else:
datetime, rate, previous_rate, results = data
if rate is None:
text = _('Analysis did not succeed '
'(see output for more details).')
self.treewidget.clear_results()
date_text = ''
else:
text_style = "<span style=\'color: #444444\'><b>%s </b></span>"
rate_style = "<span style=\'color: %s\'><b>%s</b></span>"
prevrate_style = "<span style=\'color: #666666\'>%s</span>"
color = "#FF0000"
if float(rate) > 5.:
color = "#22AA22"
elif float(rate) > 3.:
color = "#EE5500"
text = _('Global evaluation:')
text = (text_style % text)+(rate_style % (color,
('%s/10' % rate)))
if previous_rate:
text_prun = _('previous run:')
text_prun = ' (%s %s/10)' % (text_prun, previous_rate)
text += prevrate_style % text_prun
self.treewidget.set_results(filename, results)
date = to_text_string(time.strftime("%d %b %Y %H:%M", datetime),
encoding='utf8')
date_text = text_style % date
self.ratelabel.setText(text)
self.datelabel.setText(date_text)
示例7: LineProfilerWidget
# 需要导入模块: from qtpy.QtCore import QProcess [as 别名]
# 或者: from qtpy.QtCore.QProcess import waitForFinished [as 别名]
#.........这里部分代码省略.........
self.process.setWorkingDirectory(wdir)
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()]
add_pathlist_to_PYTHONPATH(env, pythonpath)
processEnvironment = QProcessEnvironment()
for envItem in env:
envName, separator, envValue = envItem.partition('=')
processEnvironment.insert(envName, envValue)
self.process.setProcessEnvironment(processEnvironment)
self.output = ''
self.error_output = ''
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, '/')
p_args = ['-lvb', '-o', '"' + self.DATAPATH + '"',
'"' + filename + '"']
if args:
p_args.extend(programs.shell_split(args))
executable = '"' + programs.find_program('kernprof') + '"'
executable += ' ' + ' '.join(p_args)
executable = executable.replace(os.sep, '/')
self.process.start(executable)
else:
p_args = ['-lvb', '-o', self.DATAPATH, filename]
if args:
p_args.extend(programs.shell_split(args))
executable = 'kernprof'
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"))
def set_running_state(self, state=True):
self.start_button.setEnabled(not state)
self.stop_button.setEnabled(state)
def read_output(self, error=False):
if error:
self.process.setReadChannel(QProcess.StandardError)
else:
self.process.setReadChannel(QProcess.StandardOutput)
qba = QByteArray()
while self.process.bytesAvailable():
if error:
qba += self.process.readAllStandardError()
else:
qba += self.process.readAllStandardOutput()
text = to_text_string(locale_codec.toUnicode(qba.data()))
if error:
self.error_output += text
else:
self.output += text
def finished(self):
self.set_running_state(False)
self.show_errorlog() # If errors occurred, show them.
self.output = self.error_output + self.output
# FIXME: figure out if show_data should be called here or
# as a signal from the combobox
self.show_data(justanalyzed=True)
def kill_if_running(self):
if self.process is not None:
if self.process.state() == QProcess.Running:
self.process.kill()
self.process.waitForFinished()
def show_data(self, justanalyzed=False):
if not justanalyzed:
self.output = None
self.log_button.setEnabled(
self.output is not None and len(self.output) > 0)
self.kill_if_running()
filename = to_text_string(self.filecombo.currentText())
if not filename:
return
self.datatree.load_data(self.DATAPATH)
self.datelabel.setText(_('Sorting data, please wait...'))
QApplication.processEvents()
self.datatree.show_tree()
text_style = "<span style=\'color: #444444\'><b>%s </b></span>"
date_text = text_style % time.strftime("%d %b %Y %H:%M",
time.localtime())
self.datelabel.setText(date_text)
示例8: ProfilerWidget
# 需要导入模块: from qtpy.QtCore import QProcess [as 别名]
# 或者: from qtpy.QtCore.QProcess import waitForFinished [as 别名]
#.........这里部分代码省略.........
self.process = QProcess(self)
self.process.setProcessChannelMode(QProcess.SeparateChannels)
self.process.setWorkingDirectory(wdir)
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)
if pythonpath is not None:
env = [to_text_string(_pth)
for _pth in self.process.systemEnvironment()]
baseshell.add_pathlist_to_PYTHONPATH(env, pythonpath)
processEnvironment = QProcessEnvironment()
for envItem in env:
envName, separator, envValue = envItem.partition('=')
processEnvironment.insert(envName, envValue)
self.process.setProcessEnvironment(processEnvironment)
self.output = ''
self.error_output = ''
p_args = ['-m', 'cProfile', '-o', self.DATAPATH]
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):
p_args.append(osp.normpath(filename).replace(os.sep, '/'))
else:
p_args.append(filename)
if args:
p_args.extend(shell_split(args))
executable = sys.executable
if executable.endswith("spyder.exe"):
# py2exe distribution
executable = "python.exe"
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"))
def set_running_state(self, state=True):
self.start_button.setEnabled(not state)
self.stop_button.setEnabled(state)
def read_output(self, error=False):
if error:
self.process.setReadChannel(QProcess.StandardError)
else:
self.process.setReadChannel(QProcess.StandardOutput)
qba = QByteArray()
while self.process.bytesAvailable():
if error:
qba += self.process.readAllStandardError()
else:
qba += self.process.readAllStandardOutput()
text = to_text_string( locale_codec.toUnicode(qba.data()) )
if error:
self.error_output += text
else:
self.output += text
def finished(self, exit_code, exit_status):
self.set_running_state(False)
self.show_errorlog() # If errors occurred, show them.
self.output = self.error_output + self.output
# FIXME: figure out if show_data should be called here or
# as a signal from the combobox
self.show_data(justanalyzed=True)
def kill_if_running(self):
if self.process is not None:
if self.process.state() == QProcess.Running:
self.process.kill()
self.process.waitForFinished()
def show_data(self, justanalyzed=False):
if not justanalyzed:
self.output = None
self.log_button.setEnabled(self.output is not None \
and len(self.output) > 0)
self.kill_if_running()
filename = to_text_string(self.filecombo.currentText())
if not filename:
return
self.datelabel.setText(_('Sorting data, please wait...'))
QApplication.processEvents()
self.datatree.load_data(self.DATAPATH)
self.datatree.show_tree()
text_style = "<span style=\'color: #444444\'><b>%s </b></span>"
date_text = text_style % time.strftime("%d %b %Y %H:%M",
time.localtime())
self.datelabel.setText(date_text)
示例9: ProcessWorker
# 需要导入模块: from qtpy.QtCore import QProcess [as 别名]
# 或者: from qtpy.QtCore.QProcess import waitForFinished [as 别名]
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]
#.........这里部分代码省略.........
示例10: AsyncClient
# 需要导入模块: from qtpy.QtCore import QProcess [as 别名]
# 或者: from qtpy.QtCore.QProcess import waitForFinished [as 别名]
#.........这里部分代码省略.........
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)
def request(self, func_name, *args, **kwargs):
"""Send a request to the server.
The response will be a dictionary the 'request_id' and the
'func_name' as well as a 'result' field with the object returned by
the function call or or an 'error' field with a traceback.
"""
if not self.is_initialized:
return
request_id = uuid.uuid4().hex
request = dict(func_name=func_name,
args=args,
kwargs=kwargs,
request_id=request_id)
self._send(request)
return request_id
def close(self):
"""Cleanly close the connection to the server.
"""
self.closing = True
self.is_initialized = False
self.timer.stop()
self.notifier.activated.disconnect(self._on_msg_received)
self.notifier.setEnabled(False)
del self.notifier
self.request('server_quit')
self.process.waitForFinished(1000)
self.process.close()
self.context.destroy()
def _on_finished(self):
"""Handle a finished signal from the process.
"""
if self.closing:
return
if self.is_initialized:
debug_print('Restarting %s' % self.name)
debug_print(self.process.readAllStandardOutput())
debug_print(self.process.readAllStandardError())
self.is_initialized = False
self.notifier.setEnabled(False)
self.run()
else:
debug_print('Errored %s' % self.name)
debug_print(self.process.readAllStandardOutput())
debug_print(self.process.readAllStandardError())
self.errored.emit()
def _on_msg_received(self):
"""Handle a message trigger from the socket.
"""
self.notifier.setEnabled(False)
while 1:
try:
resp = self.socket.recv_pyobj(flags=zmq.NOBLOCK)
except zmq.ZMQError:
self.notifier.setEnabled(True)
return
if not self.is_initialized:
self.is_initialized = True
debug_print('Initialized %s' % self.name)
self.initialized.emit()
self.timer.start(HEARTBEAT)
continue
resp['name'] = self.name
self.received.emit(resp)
def _heartbeat(self):
"""Send a heartbeat to keep the server alive.
"""
self._send(dict(func_name='server_heartbeat'))
def _send(self, obj):
"""Send an object to the server.
"""
try:
self.socket.send_pyobj(obj)
except Exception as e:
debug_print(e)
self.is_initialized = False
self._on_finished()
示例11: ProcessWorker
# 需要导入模块: from qtpy.QtCore import QProcess [as 别名]
# 或者: from qtpy.QtCore.QProcess import waitForFinished [as 别名]
class ProcessWorker(QObject):
"""Conda worker based on a QProcess for non blocking UI."""
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=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)
def _partial(self):
"""Callback for partial output."""
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):
"""Callback for communicate."""
if (not self._communicate_first and
self._process.state() == QProcess.NotRunning):
self.communicate()
elif self._fired:
self._timer.stop()
def communicate(self):
"""Retrieve information."""
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' not in stderr.lower():
if stderr.strip() and self._conda:
logger.error('{0}:\nSTDERR:\n{1}\nEND'.format(
' '.join(self._cmd_list), stderr))
elif stderr.strip() and self._pip:
logger.error("pip error: {}".format(self._cmd_list))
result[-1] = ''
if self._parse and stdout:
try:
result = json.loads(stdout), result[-1]
except Exception as error:
#.........这里部分代码省略.........
示例12: ProcessWorker
# 需要导入模块: from qtpy.QtCore import QProcess [as 别名]
# 或者: from qtpy.QtCore.QProcess import waitForFinished [as 别名]
class ProcessWorker(QObject):
"""Process worker based on a QProcess for non blocking UI."""
sig_started = Signal(object)
sig_finished = Signal(object, object, object)
sig_partial = Signal(object, object, object)
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)
def _get_encoding(self):
"""Return the encoding/codepage to use."""
enco = 'utf-8'
# Currently only cp1252 is allowed?
if WIN:
import ctypes
codepage = to_text_string(ctypes.cdll.kernel32.GetACP())
# import locale
# locale.getpreferredencoding() # Differences?
enco = 'cp' + codepage
return enco
def _set_environment(self, environ):
"""Set the environment on the QProcess."""
if environ:
q_environ = self._process.processEnvironment()
for k, v in environ.items():
q_environ.insert(k, v)
self._process.setProcessEnvironment(q_environ)
def _partial(self):
"""Callback for partial output."""
raw_stdout = self._process.readAllStandardOutput()
stdout = handle_qbytearray(raw_stdout, self._get_encoding())
if self._partial_stdout is None:
self._partial_stdout = stdout
else:
self._partial_stdout += stdout
self.sig_partial.emit(self, stdout, None)
def _communicate(self):
"""Callback for communicate."""
if (not self._communicate_first and
self._process.state() == QProcess.NotRunning):
self.communicate()
elif self._fired:
self._timer.stop()
def communicate(self):
"""Retrieve information."""
self._communicate_first = True
self._process.waitForFinished()
enco = self._get_encoding()
if self._partial_stdout is None:
raw_stdout = self._process.readAllStandardOutput()
stdout = handle_qbytearray(raw_stdout, enco)
else:
stdout = self._partial_stdout
raw_stderr = self._process.readAllStandardError()
stderr = handle_qbytearray(raw_stderr, enco)
result = [stdout.encode(enco), stderr.encode(enco)]
if PY2:
stderr = stderr.decode()
result[-1] = ''
self._result = result
if not self._fired:
self.sig_finished.emit(self, result[0], result[-1])
#.........这里部分代码省略.........