QProcess

Inheritance diagram of QProcess

Synopsis

Functions

Virtual functions

Slots

Signals

Static functions

Detailed Description

The PySide.QtCore.QProcess class is used to start external programs and to communicate with them.

Running a Process

To start a process, pass the name and command line arguments of the program you want to run as arguments to 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 Running state and emits 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 . You can then write to the process’s standard input by calling PySide.QtCore.QIODevice.write() , and read the standard output by calling PySide.QtCore.QIODevice.read() , PySide.QtCore.QIODevice.readLine() , and 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 , or for generating data to be uploaded using PySide.QtNetwork.QFtp .

Note

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

When the process exits, PySide.QtCore.QProcess reenters the NotRunning state (the initial state), and emits PySide.QtCore.QProcess.finished() .

The 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 will emit the 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.

Communicating via Channels

Processes have two predefined output channels: The standard output channel (stdout ) supplies regular console output, and the standard error channel (stderr ) usually supplies the errors that are printed by the process. These channels represent two separate streams of data. You can toggle between them by calling PySide.QtCore.QProcess.setReadChannel() . PySide.QtCore.QProcess emits 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() , or 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.

Certain processes need special environment settings in order to operate. You can set environment variables for your process by calling 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.

Note

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

Synchronous Process 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:

Calling these functions from the main thread (the thread that calls QApplication.exec() ) may cause your user interface to freeze.

The following example runs 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()

Notes for Windows Users

Some Windows commands (for example, 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 on some Windows systems), and ask the interpreter to execute the desired command.

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])
Parameters:parentPySide.QtCore.QObject

Constructs a PySide.QtCore.QProcess object with the given parent .

PySide.QtCore.QProcess.ProcessError

This enum describes the different types of errors that are reported by PySide.QtCore.QProcess .

Constant Description
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 The process crashed some time after starting successfully.
QProcess.Timedout The last waitFor...() function timed out. The state of PySide.QtCore.QProcess is unchanged, and you can try calling waitFor...() again.
QProcess.WriteError An error occurred when attempting to write to the process. For example, the process may not be running, or it may have closed its input channel.
QProcess.ReadError An error occurred when attempting to read from the process. For example, the process may not be running.
QProcess.UnknownError An unknown error occurred. This is the default return value of PySide.QtCore.QProcess.error() .
PySide.QtCore.QProcess.ProcessChannelMode

This enum describes the process channel modes of PySide.QtCore.QProcess . Pass one of these values to PySide.QtCore.QProcess.setProcessChannelMode() to set the current read channel mode.

Constant Description
QProcess.SeparateChannels PySide.QtCore.QProcess manages the output of the running process, keeping standard output and standard error data in separate internal buffers. You can select the 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 merges the output of the running process into the standard output channel (stdout). The standard error channel (stderr) will not receive any data. The standard output and standard error data of the running process are interleaved.
QProcess.ForwardedChannels PySide.QtCore.QProcess forwards the output of the running process onto the main process. Anything the child process writes to its standard output and standard error will be written to the standard output and standard error of the main process.
PySide.QtCore.QProcess.ProcessChannel

This enum describes the process channels used by the running process. Pass one of these values to PySide.QtCore.QProcess.setReadChannel() to set the current read channel of PySide.QtCore.QProcess .

Constant Description
QProcess.StandardOutput The standard output (stdout) of the running process.
QProcess.StandardError The standard error (stderr) of the running process.
PySide.QtCore.QProcess.ProcessState

This enum describes the different states of PySide.QtCore.QProcess .

Constant Description
QProcess.NotRunning The process is not running.
QProcess.Starting The process is starting, but the program has not yet been invoked.
QProcess.Running The process is running and is ready for reading and writing.
PySide.QtCore.QProcess.ExitStatus

This enum describes the different exit statuses of PySide.QtCore.QProcess .

Constant Description
QProcess.NormalExit The process exited normally.
QProcess.CrashExit The process crashed.
PySide.QtCore.QProcess.closeReadChannel(channel)
Parameters:channelPySide.QtCore.QProcess.ProcessChannel

Closes the read channel channel . After calling this function, PySide.QtCore.QProcess will no longer receive data on the channel. Any data that has already been received is still available for reading.

Call this function to save memory, if you are not interested in the output of the process.

PySide.QtCore.QProcess.closeWriteChannel()

Schedules the write channel of PySide.QtCore.QProcess to be closed. The channel will close once all data has been written to the process. After calling this function, any attempts to write to the process will fail.

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

The write channel is implicitly opened when PySide.QtCore.QProcess.start() is called.

PySide.QtCore.QProcess.environment()
Return type:list of strings

Returns the environment that 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.

Note

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

PySide.QtCore.QProcess.error()
Return type:PySide.QtCore.QProcess.ProcessError

Returns the type of error that occurred last.

PySide.QtCore.QProcess.error(error)
Parameters:errorPySide.QtCore.QProcess.ProcessError
static PySide.QtCore.QProcess.execute(program)
Parameters:program – unicode
Return type:PySide.QtCore.int

This is an overloaded function.

Starts the program program in a new process. program is a single string of text containing both the program name and its arguments. The arguments are separated by one or more spaces.

static PySide.QtCore.QProcess.execute(program, arguments)
Parameters:
  • program – unicode
  • arguments – list of strings
Return type:

PySide.QtCore.int

Starts the program program with the arguments arguments in a new process, waits for it to finish, and then returns the exit code of the process. Any data the new process writes to the console is forwarded to the calling process.

The environment and working directory are inherited from the calling process.

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

If the process cannot be started, -2 is returned. If the process crashes, -1 is returned. Otherwise, the process’ exit code is returned.

PySide.QtCore.QProcess.exitCode()
Return type:PySide.QtCore.int

Returns the exit code of the last process that finished.

PySide.QtCore.QProcess.exitStatus()
Return type:PySide.QtCore.QProcess.ExitStatus

Returns the exit status of the last process that finished.

On Windows, if the process was terminated with TerminateProcess() from another application this function will still return NormalExit unless the exit code is less than 0.

PySide.QtCore.QProcess.finished(exitCode)
Parameters:exitCodePySide.QtCore.int
PySide.QtCore.QProcess.finished(exitCode, exitStatus)
Parameters:
PySide.QtCore.QProcess.kill()

Kills the current process, causing it to exit immediately.

On 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.

See also

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

PySide.QtCore.QProcess.processChannelMode()
Return type:PySide.QtCore.QProcess.ProcessChannelMode

Returns the channel mode of the PySide.QtCore.QProcess standard output and standard error channels.

PySide.QtCore.QProcess.processEnvironment()
Return type:PySide.QtCore.QProcessEnvironment

Returns the environment that 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.

Note

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

PySide.QtCore.QProcess.readAllStandardError()
Return type:PySide.QtCore.QByteArray

Regardless of the current read channel, this function returns all data available from the standard error of the process as a PySide.QtCore.QByteArray .

PySide.QtCore.QProcess.readAllStandardOutput()
Return type:PySide.QtCore.QByteArray

Regardless of the current read channel, this function returns all data available from the standard output of the process as a PySide.QtCore.QByteArray .

PySide.QtCore.QProcess.readChannel()
Return type:PySide.QtCore.QProcess.ProcessChannel

Returns the current read channel of the PySide.QtCore.QProcess .

PySide.QtCore.QProcess.readyReadStandardError()
PySide.QtCore.QProcess.readyReadStandardOutput()
PySide.QtCore.QProcess.setEnvironment(environment)
Parameters: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")

Note

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

PySide.QtCore.QProcess.setProcessChannelMode(mode)
Parameters:modePySide.QtCore.QProcess.ProcessChannelMode

Sets the channel mode of the PySide.QtCore.QProcess standard output and standard error channels to the mode specified. This mode will be used the next time 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)
Parameters:environmentPySide.QtCore.QProcessEnvironment

Sets the environment that PySide.QtCore.QProcess will use when starting a process to the environment object.

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")

Note how, on Windows, environment variable names are case-insensitive.

PySide.QtCore.QProcess.setProcessState(state)
Parameters:statePySide.QtCore.QProcess.ProcessState

Sets the current state of the PySide.QtCore.QProcess to the state specified.

PySide.QtCore.QProcess.setReadChannel(channel)
Parameters:channelPySide.QtCore.QProcess.ProcessChannel

Sets the current read channel of the PySide.QtCore.QProcess to the given channel . The current input channel is used by the functions PySide.QtCore.QIODevice.read() , PySide.QtCore.QIODevice.readAll() , PySide.QtCore.QIODevice.readLine() , and PySide.QtCore.QIODevice.getChar() . It also determines which channel triggers PySide.QtCore.QProcess to emit PySide.QtCore.QIODevice.readyRead() .

PySide.QtCore.QProcess.setStandardErrorFile(fileName[, mode=QIODevice.Truncate])
Parameters:
  • fileName – unicode
  • modePySide.QtCore.QIODevice.OpenMode
PySide.QtCore.QProcess.setStandardInputFile(fileName)
Parameters: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.

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

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

Pipes the standard output stream of this process to the destination process’ standard input.

The following shell command:

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)
Parameters:dir – unicode

Sets the working directory to dir . PySide.QtCore.QProcess will start the process in this directory. The default behavior is to start the process in the working directory of the calling process.

Note

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

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().

Warning

This function is called by PySide.QtCore.QProcess on Unix and Mac OS X only. On Windows, it is not called.

PySide.QtCore.QProcess.start(program[, mode=QIODevice.ReadWrite])
Parameters:
  • program – unicode
  • modePySide.QtCore.QIODevice.OpenMode
PySide.QtCore.QProcess.start(program, arguments[, mode=QIODevice.ReadWrite])
Parameters:
  • program – unicode
  • arguments – list of strings
  • modePySide.QtCore.QIODevice.OpenMode
static PySide.QtCore.QProcess.startDetached(program, arguments, workingDirectory)
Parameters:
  • program – unicode
  • arguments – list of strings
  • workingDirectory – unicode
Return type:

(retval, pid)

Starts the program program with the arguments 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: The started process will run in its own session and act like a daemon.

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

The process will be started in the directory workingDirectory .

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

static PySide.QtCore.QProcess.startDetached(program, arguments)
Parameters:
  • program – unicode
  • arguments – list of strings
Return type:

PySide.QtCore.bool

Starts the program program with the given 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

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

Unix: The started process will run in its own session and act like a daemon.

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)
Parameters:program – unicode
Return type:PySide.QtCore.bool

This is an overloaded function.

Starts the program program in a new process. program is a single string of text containing both the program name and its arguments. The arguments are separated by one or more spaces.

The 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()
Return type:PySide.QtCore.QProcess.ProcessState

Returns the current state of the process.

PySide.QtCore.QProcess.stateChanged(state)
Parameters:statePySide.QtCore.QProcess.ProcessState
static PySide.QtCore.QProcess.systemEnvironment()
Return type:list of strings

Returns the environment of the calling process as a list of key=value pairs. Example:

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

This function does not cache the system environment. Therefore, it’s possible to obtain an updated version of the environment if low-level C library functions like setenv ot putenv have been called.

However, note that repeated calls to this function will recreate the list of environment variables, which is a non-trivial operation.

Note

For new code, it is recommended to use QProcessEvironment::systemEnvironment()

PySide.QtCore.QProcess.terminate()

Attempts to terminate the process.

The process may not exit as a result of calling this function (it is given the chance to prompt the user for any unsaved files, etc).

On 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.

Console applications on Windows that do not run an event loop, or whose event loop does not handle the WM_CLOSE message, can only be terminated by calling PySide.QtCore.QProcess.kill() .

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

Note

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

See also

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

PySide.QtCore.QProcess.waitForFinished([msecs=30000])
Parameters:msecsPySide.QtCore.int
Return type:PySide.QtCore.bool

Blocks until the process has finished and the PySide.QtCore.QProcess.finished() signal has been emitted, or until msecs milliseconds have passed.

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

This function can operate without an event loop. It is useful when writing non-GUI applications and when performing I/O operations in a non-GUI thread.

Warning

Calling this function from the main (GUI) thread might cause your user interface to freeze.

If msecs is -1, this function will not time out.

See also

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

PySide.QtCore.QProcess.waitForStarted([msecs=30000])
Parameters:msecsPySide.QtCore.int
Return type:PySide.QtCore.bool

Blocks until the process has started and the PySide.QtCore.QProcess.started() signal has been emitted, or until msecs milliseconds have passed.

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

This function can operate without an event loop. It is useful when writing non-GUI applications and when performing I/O operations in a non-GUI thread.

Warning

Calling this function from the main (GUI) thread might cause your user interface to freeze.

If msecs is -1, this function will not time out.

See also

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

PySide.QtCore.QProcess.workingDirectory()
Return type:unicode

If PySide.QtCore.QProcess has been assigned a working directory, this function returns the working directory that the PySide.QtCore.QProcess will enter before the program has started. Otherwise, (i.e., no directory has been assigned,) an empty string is returned, and PySide.QtCore.QProcess will use the application’s current working directory instead.