本文整理汇总了Python中qtpy.QtCore.QProcess.close方法的典型用法代码示例。如果您正苦于以下问题:Python QProcess.close方法的具体用法?Python QProcess.close怎么用?Python QProcess.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类qtpy.QtCore.QProcess
的用法示例。
在下文中一共展示了QProcess.close方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ProcessWorker
# 需要导入模块: from qtpy.QtCore import QProcess [as 别名]
# 或者: from qtpy.QtCore.QProcess import close [as 别名]
#.........这里部分代码省略.........
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]
self._result = result
self.sig_finished.emit(self, result[0], result[-1])
if result[-1]:
logger.error(str(('error', result[-1])))
self._fired = True
return result
def close(self):
"""
"""
self._process.close()
def is_finished(self):
"""
"""
return self._process.state() == QProcess.NotRunning and self._fired
def start(self):
"""
"""
logger.debug(str(' '.join(self._cmd_list)))
if not self._fired:
self._partial_ouput = None
self._process.start(self._cmd_list[0], self._cmd_list[1:])
self._timer.start()
else:
raise CondaProcessWorker('A Conda ProcessWorker can only run once '
'per method call.')
示例2: ProcessWorker
# 需要导入模块: from qtpy.QtCore import QProcess [as 别名]
# 或者: from qtpy.QtCore.QProcess import close [as 别名]
#.........这里部分代码省略.........
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:
result = stdout, str(error)
if 'error' in result[0]:
if not isinstance(result[0], dict):
result = {'error': str(result[0])}, None
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]
self._result = result
self.sig_finished.emit(self, result[0], result[-1])
if result[-1]:
logger.error(str(('error', result[-1])))
self._fired = True
return result
def close(self):
"""Close the running process."""
self._process.close()
def is_finished(self):
"""Return True if worker has finished processing."""
return self._process.state() == QProcess.NotRunning and self._fired
def start(self):
"""Start process."""
logger.debug(str(' '.join(self._cmd_list)))
if not self._fired:
self._partial_ouput = None
self._process.start(self._cmd_list[0], self._cmd_list[1:])
self._timer.start()
else:
raise CondaProcessWorker('A Conda ProcessWorker can only run once '
'per method call.')
示例3: AsyncClient
# 需要导入模块: from qtpy.QtCore import QProcess [as 别名]
# 或者: from qtpy.QtCore.QProcess import close [as 别名]
class AsyncClient(QObject):
"""
A class which handles a connection to a client through a QProcess.
"""
# Emitted when the client has initialized.
initialized = Signal()
# Emitted when the client errors.
errored = Signal()
# Emitted when a request response is received.
received = Signal(object)
def __init__(self, target, executable=None, name=None,
extra_args=None, libs=None, cwd=None, env=None):
super(AsyncClient, self).__init__()
self.executable = executable or sys.executable
self.extra_args = extra_args
self.target = target
self.name = name or self
self.libs = libs
self.cwd = cwd
self.env = env
self.is_initialized = False
self.closing = False
self.context = zmq.Context()
QApplication.instance().aboutToQuit.connect(self.close)
# Set up the heartbeat timer.
self.timer = QTimer(self)
self.timer.timeout.connect(self._heartbeat)
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)
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.
#.........这里部分代码省略.........
示例4: ProcessWorker
# 需要导入模块: from qtpy.QtCore import QProcess [as 别名]
# 或者: from qtpy.QtCore.QProcess import close [as 别名]
#.........这里部分代码省略.........
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])
self._fired = True
return result
def close(self):
"""Close the running process."""
self._process.close()
def is_finished(self):
"""Return True if worker has finished processing."""
return self._process.state() == QProcess.NotRunning and self._fired
def _start(self):
"""Start process."""
if not self._fired:
self._partial_ouput = None
self._process.start(self._cmd_list[0], self._cmd_list[1:])
self._timer.start()
def terminate(self):
"""Terminate running processes."""
if self._process.state() == QProcess.Running:
try:
self._process.terminate()
except Exception:
pass
self._fired = True
def start(self):
"""Start worker."""
if not self._started:
self.sig_started.emit(self)
self._started = True