QProcess

概要

函数

虚函数

信号

静态函数

详细描述

PySide.QtCore.QProcess 类用于启动外部程序并与之通信。

运行进程

要启动进程,把希望运行的程序名称和命令行自变量作为自变量传递给 PySide.QtCore.QProcess.start() . Arguments are supplied as individual strings in a PySide.QtCore.QStringList .

For example, the following code snippet runs the analog clock example in the Motif style on X11 platforms by passing strings containing “-style” and “motif” as two items in the list of arguments:

...
...
program = "./path/to/Qt/examples/widgets/analogclock"
arguments = ["-style", "motif"]
myProcess = QProcess(parent)
myProcess.start(program, arguments)
											

PySide.QtCore.QProcess then enters the Starting state, and when the program has started, PySide.QtCore.QProcess enters the 运行 状态并发射 PySide.QtCore.QProcess.started() .

PySide.QtCore.QProcess allows you to treat a process as a sequential I/O device. You can write to and read from the process just as you would access a network connection using PySide.QtNetwork.QTcpSocket 。然后可以写入进程标准输入通过调用 PySide.QtCore.QIODevice.write() , and read the standard output by calling PySide.QtCore.QIODevice.read() , PySide.QtCore.QIODevice.readLine() ,和 PySide.QtCore.QIODevice.getChar() . Because it inherits PySide.QtCore.QIODevice , PySide.QtCore.QProcess can also be used as an input source for PySide.QtXml.QXmlReader ,或对于生成要上传的数据使用 PySide.QtNetwork.QFtp .

注意

On Windows CE and Symbian, reading and writing to a process is not supported.

When the process exits, PySide.QtCore.QProcess reenters the NotRunning 状态 (初始状态),并发射 PySide.QtCore.QProcess.finished() .

PySide.QtCore.QProcess.finished() signal provides the exit code and exit status of the process as arguments, and you can also call PySide.QtCore.QProcess.exitCode() to obtain the exit code of the last process that finished, and PySide.QtCore.QProcess.exitStatus() to obtain its exit status. If an error occurs at any point in time, PySide.QtCore.QProcess 将发射 PySide.QtCore.QProcess.error() signal. You can also call PySide.QtCore.QProcess.error() to find the type of error that occurred last, and PySide.QtCore.QProcess.state() to find the current process state.

凭借通道通信

进程有 2 个预定义输出通道:标准输出通道 ( stdout ) 提供常规控制台输出,和标准错误通道 ( stderr ) 通常提供由进程打印的错误。这些通道表示 2 个单独数据流。可以在它们之间切换通过调用 PySide.QtCore.QProcess.setReadChannel() . PySide.QtCore.QProcess 发射 PySide.QtCore.QIODevice.readyRead() when data is available on the current read channel. It also emits PySide.QtCore.QProcess.readyReadStandardOutput() when new standard output data is available, and when new standard error data is available, PySide.QtCore.QProcess.readyReadStandardError() is emitted. Instead of calling PySide.QtCore.QIODevice.read() , PySide.QtCore.QIODevice.readLine() ,或 PySide.QtCore.QIODevice.getChar() , you can explicitly read all data from either of the two channels by calling PySide.QtCore.QProcess.readAllStandardOutput() or PySide.QtCore.QProcess.readAllStandardError() .

The terminology for the channels can be misleading. Be aware that the process's output channels correspond to PySide.QtCore.QProcess ‘s read channels, whereas the process's input channels correspond to PySide.QtCore.QProcess ‘s write channels. This is because what we read using PySide.QtCore.QProcess is the process's output, and what we write becomes the process's input.

PySide.QtCore.QProcess can merge the two output channels, so that standard output and standard error data from the running process both use the standard output channel. Call PySide.QtCore.QProcess.setProcessChannelMode() with MergedChannels before starting the process to activative this feature. You also have the option of forwarding the output of the running process to the calling, main process, by passing ForwardedChannels as the argument.

某些进程需要特殊环境设置才能运转。可以为进程设置环境变量通过调用 PySide.QtCore.QProcess.setEnvironment() . To set a working directory, call PySide.QtCore.QProcess.setWorkingDirectory() . By default, processes are run in the current working directory of the calling process.

注意

On Symbian, setting environment or working directory is not supported. The working directory will always be the private directory of the running process.

注意

On QNX, setting the working directory may cause all application threads, with the exception of the PySide.QtCore.QProcess caller thread, to temporarily freeze, owing to a limitation in the operating system.

同步进程 API

PySide.QtCore.QProcess provides a set of functions which allow it to be used without an event loop, by suspending the calling thread until certain signals are emitted:

从主线程调用这些函数 (线程调用 QApplication.exec() ) may cause your user interface to freeze.

以下范例运行 gzip to compress the string “Qt rocks!”, without an event loop:

gzip = QProcess()
gzip.start("gzip", ["-c"])
if not gzip.waitForStarted():
    return False
gzip.write("Qt rocks!")
gzip.closeWriteChannel()
if not gzip.waitForFinished():
    return False
result = gzip.readAll()
											

Windows 用户注意事项

某些 Windows 命令 (例如, dir ) are not provided by separate applications, but by the command interpreter itself. If you attempt to use PySide.QtCore.QProcess to execute these commands directly, it won't work. One possible solution is to execute the command interpreter itself ( cmd.exe 在某些 Windows 系统),和要求解释器执行期望命令。

Symbian Platform Security Requirements

On Symbian, processes which use the functions PySide.QtCore.QProcess.kill() or PySide.QtCore.QProcess.terminate() must have the PowerMgmt platform security capability. If the client process lacks this capability, these functions will fail.

Platform security capabilities are added via the TARGET.CAPABILITY qmake variable.

class PySide.QtCore. QProcess ( [ parent=None ] )
参数: parent PySide.QtCore.QObject

构造 PySide.QtCore.QProcess 对象采用给定 parent .

PySide.QtCore.QProcess. ProcessError

此枚举描述错误的不同类型,报告通过 PySide.QtCore.QProcess .

常量 描述
QProcess.FailedToStart The process failed to start. Either the invoked program is missing, or you may have insufficient permissions to invoke the program.
QProcess.Crashed 进程有时崩溃在成功启动后。
QProcess.Timedout 最后 waitFor...() 函数超时。状态对于 PySide.QtCore.QProcess 不变,和可以再次试着调用 waitFor...()。
QProcess.WriteError 发生错误当试图写入进程时。例如,进程可能未运行,或它可能已关闭其输入通道。
QProcess.ReadError 发生错误当试图从进程读取时。例如,进程可能未运行。
QProcess.UnknownError 发生未知错误。这是默认返回值为 PySide.QtCore.QProcess.error() .
PySide.QtCore.QProcess. ProcessChannelMode

This enum describes the process channel modes of PySide.QtCore.QProcess 。将这些值之一传递给 PySide.QtCore.QProcess.setProcessChannelMode() to set the current read channel mode.

常量 描述
QProcess.SeparateChannels PySide.QtCore.QProcess 管理正运行进程的输出,将标准输出和标准错误数据保持在单独内部缓冲中。可以选择 PySide.QtCore.QProcess ‘s current read channel by calling PySide.QtCore.QProcess.setReadChannel() . This is the default channel mode of PySide.QtCore.QProcess .
QProcess.MergedChannels PySide.QtCore.QProcess 将正运行进程的输出合并到标准输出通道 ( stdout )。标准错误通道 ( stderr ) will not receive any data. The standard output and standard error data of the running process are interleaved.
QProcess.ForwardedChannels PySide.QtCore.QProcess 将正运行进程的输出转发到主进程。由子级进程写入其标准输出和标准错误的任何内容,都将写入主进程的标准输出和标准错误。
PySide.QtCore.QProcess. ProcessChannel

此枚举描述正运行进程所使用的进程通道。传递这些值之一给 PySide.QtCore.QProcess.setReadChannel() to set the current read channel of PySide.QtCore.QProcess .

常量 描述
QProcess.StandardOutput 正运行进程的 stdout (标准输出)。
QProcess.StandardError 正运行进程的 stderr (标准错误)。
PySide.QtCore.QProcess. ProcessState

此枚举描述不同状态为 PySide.QtCore.QProcess .

常量 描述
QProcess.NotRunning 进程未运行。
QProcess.Starting 进程正在启动,但尚未援引程序。
QProcess.Running 进程正在运行且读写就绪。
PySide.QtCore.QProcess. ExitStatus

此枚举描述不同退出状态为 PySide.QtCore.QProcess .

常量 描述
QProcess.NormalExit 进程正常退出。
QProcess.CrashExit 进程崩溃。
PySide.QtCore.QProcess. closeReadChannel ( channel )
参数: channel PySide.QtCore.QProcess.ProcessChannel

关闭读取通道 channel 。在调用此函数后, PySide.QtCore.QProcess 将不再接收通道数据。任何已收到的数据仍可用于读取。

调用此函数以节省内存,若对进程的输出不感兴趣。

PySide.QtCore.QProcess. closeWriteChannel ( )

调度写入通道对于 PySide.QtCore.QProcess 要被关闭。一旦所有数据被写入进程,通道就将关闭。在调用此函数后,任何写入进程的试图都将失败。

Closing the write channel is necessary for programs that read input data until the channel has been closed. For example, the program “more” is used to display text data in a console on both Unix and Windows. But it will not display the text data until PySide.QtCore.QProcess ‘s write channel has been closed. Example:

more = QProcess()
more.start("more")
more.write("Text to display")
more.closeWriteChannel()
#QProcess will emit readyRead() once "more" starts printing
												

写入通道被隐式打开当 PySide.QtCore.QProcess.start() 被调用。

PySide.QtCore.QProcess. environment ( )
返回类型: 字符串列表

返回环境 PySide.QtCore.QProcess will use when starting a process, or an empty PySide.QtCore.QStringList if no environment has been set using PySide.QtCore.QProcess.setEnvironment() or setEnvironmentHash(). If no environment has been set, the environment of the calling process will be used.

注意

The environment settings are ignored on Windows CE and Symbian, as there is no concept of an environment.

PySide.QtCore.QProcess. error ( )
返回类型: PySide.QtCore.QProcess.ProcessError

返回最后发生的错误类型。

PySide.QtCore.QProcess. error ( error )
参数: error PySide.QtCore.QProcess.ProcessError
static PySide.QtCore.QProcess. execute ( program , arguments )
参数:
  • program – unicode
  • arguments – list of strings
返回类型:

PySide.QtCore.int

启动程序 program 采用自变量 arguments 在新进程中,等待它完成,然后返回进程的退出代码。新进程写入控制台的任何数据会被转发给调用进程。

环境和工作目录继承自调用进程。

On Windows, arguments that contain spaces are wrapped in quotes.

若进程无法启动,返回 -2。若进程崩溃,返回 -1。否则,返回进程的退出代码。

static PySide.QtCore.QProcess. execute ( program )
参数: program – unicode
返回类型: PySide.QtCore.int

这是重载函数。

启动程序 program 在新的进程中。 program is a single string of text containing both the program name and its arguments. The arguments are separated by one or more spaces.

PySide.QtCore.QProcess. exitCode ( )
返回类型: PySide.QtCore.int

返回最后完成进程的退出代码。

PySide.QtCore.QProcess. exitStatus ( )
返回类型: PySide.QtCore.QProcess.ExitStatus

返回最后完成的进程退出状态。

On Windows, if the process was terminated with TerminateProcess() from another application this function will still return NormalExit 除非退出代码小于 0。

PySide.QtCore.QProcess. finished ( exitCode , exitStatus )
参数:
PySide.QtCore.QProcess. finished ( exitCode )
参数: exitCode PySide.QtCore.int
PySide.QtCore.QProcess. kill ( )

杀除当前进程,导致它立即退出。

在 Windows, PySide.QtCore.QProcess.kill() uses TerminateProcess, and on Unix and Mac OS X, the SIGKILL signal is sent to the process.

On Symbian, this function requires platform security capability PowerMgmt . If absent, the process will panic with KERN-EXEC 46.

注意

Killing running processes from other processes will typically cause a panic in Symbian due to platform security.

另请参阅

Symbian Platform Security Requirements PySide.QtCore.QProcess.terminate()

PySide.QtCore.QProcess. processChannelMode ( )
返回类型: PySide.QtCore.QProcess.ProcessChannelMode

返回通道模式对于 PySide.QtCore.QProcess 标准输出和标准错误通道。

PySide.QtCore.QProcess. processEnvironment ( )
返回类型: PySide.QtCore.QProcessEnvironment

返回环境 PySide.QtCore.QProcess will use when starting a process, or an empty object if no environment has been set using PySide.QtCore.QProcess.setEnvironment() or PySide.QtCore.QProcess.setProcessEnvironment() . If no environment has been set, the environment of the calling process will be used.

注意

The environment settings are ignored on Windows CE, as there is no concept of an environment.

PySide.QtCore.QProcess. readAllStandardError ( )
返回类型: PySide.QtCore.QByteArray

不管当前读取通道,此函数从进程标准错误返回所有可用数据按 PySide.QtCore.QByteArray .

PySide.QtCore.QProcess. readAllStandardOutput ( )
返回类型: PySide.QtCore.QByteArray

不管当前读取通道,此函数从进程标准输出返回所有可用数据按 PySide.QtCore.QByteArray .

PySide.QtCore.QProcess. readChannel ( )
返回类型: PySide.QtCore.QProcess.ProcessChannel

返回当前读取通道为 PySide.QtCore.QProcess .

PySide.QtCore.QProcess. readyReadStandardError ( )
PySide.QtCore.QProcess. readyReadStandardOutput ( )
PySide.QtCore.QProcess. setEnvironment ( environment )
参数: environment – list of strings

Sets the environment that PySide.QtCore.QProcess will use when starting a process to the environment specified which consists of a list of key=value pairs.

For example, the following code adds the C:\\BIN directory to the list of executable paths ( PATHS ) on Windows:

import re
from PySide.QtCore import QProcess
process = QProcess()
env = QProcess.systemEnvironment()
env.append("TMPDIR=C:\\MyApp\\temp") # Add an environment variable
regex = re.compile(r'^PATH=(.*)', re.IGNORECASE)
env = [regex.sub(r'PATH=\1;C:\\Bin', var) for var in env]
process.setEnvironment(env)
process.start("myapp")
												

注意

This function is less efficient than the PySide.QtCore.QProcess.setProcessEnvironment() 函数。

PySide.QtCore.QProcess. setProcessChannelMode ( mode )
参数: mode PySide.QtCore.QProcess.ProcessChannelMode

设置通道模式为 PySide.QtCore.QProcess 标准输出和标准错误通道到 mode 指定。会使用此模式当下次 PySide.QtCore.QProcess.start() is called. For example:

builder = QProcess()
builder.setProcessChannelMode(QProcess.MergedChannels)
builder.start("make", ["-j2"])
import sys
if not builder.waitForFinished():
    sys.stderr.write("Make failed:" + builder.errorString())
else
    sys.stderr.write("Make output:" + builder.readAll())
											
PySide.QtCore.QProcess. setProcessEnvironment ( environment )
参数: environment PySide.QtCore.QProcessEnvironment

Sets the environment that PySide.QtCore.QProcess will use when starting a process to the environment 对象。

For example, the following code adds the C:\\BIN directory to the list of executable paths ( PATHS ) on Windows and sets TMPDIR :

process = QProcess()
env = QProcessEnvironment.systemEnvironment()
env.insert("TMPDIR", "C:\\MyApp\\temp") # Add an environment variable
env.insert("PATH", env.value("Path") + ";C:\\Bin")
process.setProcessEnvironment(env)
process.start("myapp")
												

注意:在 Windows,环境变量名称是不区分大小写的。

PySide.QtCore.QProcess. setProcessState ( state )
参数: state PySide.QtCore.QProcess.ProcessState

设置当前状态为 PySide.QtCore.QProcess state 指定。

PySide.QtCore.QProcess. setReadChannel ( channel )
参数: channel PySide.QtCore.QProcess.ProcessChannel

设置当前读取通道为 PySide.QtCore.QProcess 到给定 channel 。当前输入通道用于函数 PySide.QtCore.QIODevice.read() , PySide.QtCore.QIODevice.readAll() , PySide.QtCore.QIODevice.readLine() ,和 PySide.QtCore.QIODevice.getChar() . It also determines which channel triggers PySide.QtCore.QProcess 以发射 PySide.QtCore.QIODevice.readyRead() .

PySide.QtCore.QProcess. setStandardErrorFile ( fileName [ , mode=QIODevice.Truncate ] )
参数:
  • fileName – unicode
  • mode PySide.QtCore.QIODevice.OpenMode
PySide.QtCore.QProcess. setStandardInputFile ( fileName )
参数: fileName – unicode

Redirects the process' standard input to the file indicated by fileName . When an input redirection is in place, the PySide.QtCore.QProcess object will be in read-only mode (calling PySide.QtCore.QIODevice.write() will result in error).

If the file fileName does not exist at the moment PySide.QtCore.QProcess.start() is called or is not readable, starting the process will fail.

调用 PySide.QtCore.QProcess.setStandardInputFile() after the process has started has no effect.

PySide.QtCore.QProcess. setStandardOutputFile ( fileName [ , mode=QIODevice.Truncate ] )
参数:
  • fileName – unicode
  • mode PySide.QtCore.QIODevice.OpenMode
PySide.QtCore.QProcess. setStandardOutputProcess ( destination )
参数: destination PySide.QtCore.QProcess

将此进程的标准输出流管道到 destination 进程的标准输入。

以下 Shell 命令:

command1 | command2
												

Can be accomplished with QProcesses with the following code:

process1 = QProcess()
process2 = QProcess()
process1.setStandardOutputProcess(process2)
process1.start("command1")
process2.start("command2")
												
PySide.QtCore.QProcess. setWorkingDirectory ( dir )
参数: dir – unicode

把工作目录设为 dir . PySide.QtCore.QProcess 将在此目录下启动进程。默认行为是在调用进程的工作目录下启动进程。

注意

The working directory setting is ignored on Symbian; the private directory of the process is considered its working directory.

注意

在 QNX,这可能导致所有应用程序线程被临时冻结。

PySide.QtCore.QProcess. setupChildProcess ( )

This function is called in the child process context just before the program is executed on Unix or Mac OS X (i.e., after fork() , but before execve() ). Reimplement this function to do last minute initialization of the child process. Example:

class SandboxProcess(QProcess):
    def setupChildProcess(self)
        # Drop all privileges in the child process, and enter
        # a chroot jail.
        os.setgroups(0, 0)
        os.chroot("/etc/safe")
        os.chdir("/")
        os.setgid(safeGid)
        os.setuid(safeUid)
        os.umask(0)
											

You cannot exit the process (by calling exit(), for instance) from this function. If you need to stop the program before it starts execution, your workaround is to emit PySide.QtCore.QProcess.finished() and then call exit().

警告

此函数被调用由 PySide.QtCore.QProcess on Unix and Mac OS X only. On Windows and QNX, it is not called.

PySide.QtCore.QProcess. start ( program , arguments [ , mode=QIODevice.ReadWrite ] )
参数:
  • program – unicode
  • arguments – list of strings
  • mode PySide.QtCore.QIODevice.OpenMode
PySide.QtCore.QProcess. start ( program [ , mode=QIODevice.ReadWrite ] )
参数:
  • program – unicode
  • mode PySide.QtCore.QIODevice.OpenMode
static PySide.QtCore.QProcess. startDetached ( program , arguments , workingDirectory )
参数:
  • program – unicode
  • arguments – list of strings
  • workingDirectory – unicode
返回类型:

(retval, pid)

启动程序 program 采用自变量 arguments in a new process, and detaches from it. Returns true on success; otherwise returns false. If the calling process exits, the detached process will continue to live.

Note that arguments that contain spaces are not passed to the process as separate arguments.

Unix: 启动进程将在它自己的会话中运行,且行动像守护程序。

Windows: Arguments that contain spaces are wrapped in quotes. The started process will run as a regular standalone process.

进程将被启动在目录 workingDirectory .

注意

在 QNX,这可能导致所有应用程序线程被临时冻结。

If the function is successful then *``pid`` is set to the process identifier of the started process.

static PySide.QtCore.QProcess. startDetached ( program , arguments )
参数:
  • program – unicode
  • arguments – list of strings
返回类型:

PySide.QtCore.bool

启动程序 program 采用给定 arguments in a new process, and detaches from it. Returns true on success; otherwise returns false. If the calling process exits, the detached process will continue to live.

注意

Arguments that contain spaces are not passed to the process as separate arguments.

Unix: 启动进程将在它自己的会话中运行,且行动像守护程序。

Windows: Arguments that contain spaces are wrapped in quotes. The started process will run as a regular standalone process.

static PySide.QtCore.QProcess. startDetached ( program )
参数: program – unicode
返回类型: PySide.QtCore.bool

这是重载函数。

启动程序 program 在新的进程中。 program is a single string of text containing both the program name and its arguments. The arguments are separated by one or more spaces.

program string can also contain quotes, to ensure that arguments containing spaces are correctly supplied to the new process.

PySide.QtCore.QProcess. started ( )
PySide.QtCore.QProcess. state ( )
返回类型: PySide.QtCore.QProcess.ProcessState

返回进程的当前状态。

PySide.QtCore.QProcess. stateChanged ( state )
参数: state PySide.QtCore.QProcess.ProcessState
static PySide.QtCore.QProcess. systemEnvironment ( )
返回类型: 字符串列表

以 key=value 对列表形式返回调用进程的环境。范例:

environment = QProcess.systemEnvironment()
# environment = [PATH=/usr/bin:/usr/local/bin",
#                "USER=greg", "HOME=/home/greg"]
												

此函数不缓存系统环境。因此,获得环境的更新版本是可能的,若低级 C 库函数像 setenv ot putenv 有被调用。

不管怎样,注意,重复调用此函数将重新创建环境变量列表 (非通俗操作)。

注意

对于新代码,推荐使用 QProcessEnvironment.systemEnvironment()

PySide.QtCore.QProcess. terminate ( )

试图终止进程。

进程可能不会因调用此函数而退出 (它有机会提示用户是否有未保存的文件,等等)。

在 Windows, PySide.QtCore.QProcess.terminate() posts a WM_CLOSE message to all toplevel windows of the process and then to the main thread of the process itself. On Unix and Mac OS X the SIGTERM signal is sent.

不运行事件循环的 Windows 控制台应用程序 (或其事件循环不处理 WM_CLOSE 消息),只可被终止通过调用 PySide.QtCore.QProcess.kill() .

On Symbian, this function requires platform security capability PowerMgmt . If absent, the process will panic with KERN-EXEC 46.

注意

Terminating running processes from other processes will typically cause a panic in Symbian due to platform security.

另请参阅

Symbian Platform Security Requirements PySide.QtCore.QProcess.kill()

PySide.QtCore.QProcess. waitForFinished ( [ msecs=30000 ] )
参数: msecs PySide.QtCore.int
返回类型: PySide.QtCore.bool

阻塞直到进程已完成且 PySide.QtCore.QProcess.finished() signal has been emitted, or until msecs 毫秒已过去。

Returns true if the process finished; otherwise returns false (if the operation timed out, if an error occurred, or if this PySide.QtCore.QProcess 已完成)。

可以在没有事件循环的情况下操作此函数。它很有用,当编写非 GUI 应用程序和在非 GUI 线程中履行 I/O 操作时。

警告

从主 GUI 线程调用此函数可能导致用户界面被冻结。

若 msecs 为 -1,此函数不会超时。

另请参阅

PySide.QtCore.QProcess.finished() PySide.QtCore.QProcess.waitForStarted() PySide.QtCore.QProcess.waitForReadyRead() PySide.QtCore.QProcess.waitForBytesWritten()

PySide.QtCore.QProcess. waitForStarted ( [ msecs=30000 ] )
参数: msecs PySide.QtCore.int
返回类型: PySide.QtCore.bool

阻塞直到进程启动且 PySide.QtCore.QProcess.started() signal has been emitted, or until msecs 毫秒已过去。

Returns true if the process was started successfully; otherwise returns false (if the operation timed out or if an error occurred).

可以在没有事件循环的情况下操作此函数。它很有用,当编写非 GUI 应用程序和在非 GUI 线程中履行 I/O 操作时。

警告

从主 GUI 线程调用此函数可能导致用户界面被冻结。

若 msecs 为 -1,此函数不会超时。

另请参阅

PySide.QtCore.QProcess.started() PySide.QtCore.QProcess.waitForReadyRead() PySide.QtCore.QProcess.waitForBytesWritten() PySide.QtCore.QProcess.waitForFinished()

PySide.QtCore.QProcess. workingDirectory ( )
返回类型: unicode

PySide.QtCore.QProcess 已赋值工作目录,此函数返回工作目录 PySide.QtCore.QProcess 将在程序开始之前进入。否则,返回空字符串 (即:没有赋值目录),且 PySide.QtCore.QProcess 将使用应用程序的当前工作目录取而代之。