Python process exit status

How to Query Process Status

You can query the status of a multiprocessing.Process via attributes such as name, daemon and pid.

In this tutorial you will discover how to query the status of a process in Python.

Need to Query Process Attributes

A process is a running instance of a computer program.

Every Python program is executed in a Process, which is a new instance of the Python interpreter. This process has the name MainProcess and has one thread used to execute the program instructions called the MainThread. Both processes and threads are created and managed by the underlying operating system.

Sometimes we may need to create new child processes in our program in order to execute code concurrently.

Python provides the ability to create and manage new processes via the multiprocessing.Process class.

You can learn more about multiprocessing in the tutorial:

An instance of the multiprocessing.Process class provides a handle of a Python process. As such, it provides attributes that we can use to query properties and the status of the underlying process.

How can we query attributes of a multiprocessing.Process instance?

Run your loops using all CPUs, download my FREE book to learn how.

How to Query Process Attributes

The multiprocessing.Process class provides instance attributes that can be used to query the status of the process.

This includes queries such as the process name and whether the process is currently alive.

The following provides a list of multiprocessing.Process attributes that we can query:

  • name: Get or set the name of the process.
  • daemon: Get or set whether the process is a daemon process or not.
  • pid: Get the process identifier, once it is started.
  • exitcode: Get the exit code for the process, once it is terminated.
  • authkey: Get the authentication key for a process.
  • sentinel: Get the sentinel object for a process.
  • is_alive(): Check if the process is currently running.

Only the “name” and “daemon” attributes can be both accessed (retrieved) and set (assigned) after the multiprocessing.Process has been instantiated. The “daemon” attribute cannot be changed after the start() function has been called to run the thread.

The “pid” attribute is read-only and returns a positive integer value after the process has started. The “exitcode” attribute is read-only and returns an integer value after the process has terminated.

The “is_alive()” function (not an attribute) returns a boolean value as to whether the read is currently executing its run() function, e.g. running, or not.

Now that we are familiar with how to query the status of a process, let’s look at some examples.

Confused by the multiprocessing module API?
Download my FREE PDF cheat sheet

Example of Querying Process Name

The parent process has the name “MainProcess“.

Child processes are named automatically in a somewhat unique manner within each process with the form “Process-%d” where %d is the integer indicating the process number created by the parent process, e.g. Process-1 for the first process created.

We can access the name of a process via the multiprocessing.Process.name attribute, for example:

Источник

Process Exit Codes in Python

You can set an exit code for a process via sys.exit() and retrieve the exit code via the exitcode attribute on the multiprocessing.Process class.

In this tutorial you will discover how to get and set exit codes for processes in Python.

Need Process Exit Codes

A process is a running instance of a computer program.

Every Python program is executed in a Process, which is a new instance of the Python interpreter. This process has the name MainProcess and has one thread used to execute the program instructions called the MainThread. Both processes and threads are created and managed by the underlying operating system.

Sometimes we may need to create new child processes in our program in order to execute code concurrently.

Python provides the ability to create and manage new processes via the multiprocessing.Process class.

In multiprocessing, we may need to report the success or failure of a task executed by a child process to other processes.

This can be achieved using exit codes.

What are exit codes and how can we use them between processes in Python?

Run your loops using all CPUs, download my FREE book to learn how.

How to Use Exit Codes in Python

An exit code or exit status is a way for one process to share with another whether it is finished and if so whether it finished successfully or not.

The exit status of a process in computer programming is a small number passed from a child process (or callee) to a parent process (or caller) when it has finished executing a specific procedure or delegated task.

— Exit status, Wikipedia.

An exit code is typically an integer value to represent success or failure of the process, but may also have an associated string message.

Let’s take a closer look at how we might set an exit code in a process and how another process might check the exit code of a process.

How to Set an Exit Code

A process can set the exit code automatically or explicitly.

For example, if the process exits normally, the exit code will be set to zero. If the process terminated with an error or exception, the exit code will be set to one.

A process can also set its exit code when explicitly exiting.

This can be achieved by calling the sys.exit() function and passing the exit code as an argument.

The sys.exit() function will raise a SystemExit exception in the current process, which will terminate the process.

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object.

— sys — System-specific parameters and functions

This function must be called in the main thread of the process and assumes that the SystemExit exception is not handled.

An argument value of 0 indicates a successful exit.

Источник

Exit a Process with sys.exit() in Python

You can call sys.exit() to exit a process.

In this tutorial you will discover how to use sys.exit() with parent and child processes in Python.

What is sys.exit()

The sys.exit() function is described as exiting the Python interpreter.

Raise a SystemExit exception, signaling an intention to exit the interpreter.

— sys — System-specific parameters and functions

When called, the sys.exit() function will raise a SystemExit exception.

This exception is (typically) not caught and bubbles up to the top of a stack of the running thread, causing it and the process to exit.

… This allows the exception to properly propagate up and cause the interpreter to exit. When it is not handled, the Python interpreter exits; no stack traceback is printed.

— Built-in Exceptions

The sys.exit() function takes an argument that indicates the success or failure of the exit status.

A value of None (the default) or zero indicates a successful , whereas a larger value indicates an unsuccessful exit.

If the value is an integer, it specifies the system exit status (passed to C’s exit() function); if it is None, the exit status is zero; if it has another type (such as a string), the object’s value is printed and the exit status is one.

— Built-in Exceptions

Importantly, finally operations in try-except-finally and try-finally patterns are executed. This allows a program to clean-up before exiting.

Cleanup actions specified by finally clauses of try statements are honored …

— sys — System-specific parameters and functions

In multiprocessing programming, we may make calls to sys.exit() to close our program.

How does sys.exit() interact with the main process and child processes in Python?

Run your loops using all CPUs, download my FREE book to learn how.

sys.exit() and Exit Codes

Each Python process has an exit code.

The process exitcode is set automatically, for example:

  • If the process is still running, the exitcode will be None.
  • If the process exited normally, the exitcode will be 0.
  • If the process terminated with an uncaught exception, the exitcode will be 1.

The exitcode can also be set via a call to sys.exit().

For example, a child process may exit with a call to sys.exit() with no arguments.

The child process will terminate and the exitcode will be set to 0.

Confused by the multiprocessing module API?
Download my FREE PDF cheat sheet

How to Use sys.exit()

The sys.exit() function is used by simply making the function call.

A normal exit can be achieved by calling the function with no argument, e.g. defaulting to a value of None.

A normal exit can also be achieved by passing the value of None or 0 as an argument.

An unsuccessful exit can be signaled by passing a value other than 0 or None.

This may be an integer exit code, such as 1.

Alternatively, it may be a string value that may be reported as part of the exit.

Now that we know how to use sys.exit(), let’s look at some worked examples.

Free Python Multiprocessing Course

Download my multiprocessing API cheat sheet and as a bonus you will get FREE access to my 7-day email course.

Discover how to use the Python multiprocessing module including how to create and start child processes and how to use a mutex locks and semaphores.

Exit the Main Process

We can explore how to exit the main process using sys.exit().

In this example we will report a message, block for a moment, then exit successfully. We will also include code after the call to sys.exit() to demonstrate that indeed the program is terminated and additional code is unreachable.

The complete example is listed below.

Running the example first reports a message that the main process is running.

The process then blocks for two seconds.

Once awake, the process reports a message then calls sys.exit() to exit normally. The program terminates and the final print statement is never reached.

When the sys.exit() function is called, a SystemExit exception is raised in the main thread. The main thread terminates. As there are no other threads and no child processes, the main process terminates.

Next, let’s explore calling sys.exit() from a child process.

Overwheled by the python concurrency APIs?
Find relief, download my FREE Python Concurrency Mind Maps

Exit a Child Process

We can explore calling sys.exit() from a child process.

In this example we will execute a new function in a child process. The child process will report a message, block for a moment, then call exit with a value of one to indicate an unsuccessful exit. It will also include code after the call to exit to confirm that additional code is not reachable. The main process will report the status and exitcode of the child process.

First, we can define a function to execute in a child process.

The function reports a message, blocks, then exits with an exit code of one.

The task() function below implements this.

Next, in the main process we can create a new multiprocessing.Process instance and configure it to execute our task() function.

We can then start the process and wait for it to terminate.

Finally, we can check the running status of the child process to confirm it has terminated and report the exitcode.

Tying this together, the complete example is listed below.

Running the example first creates a child process configured to execute our target function.

The main process then starts the child process then blocks until it terminates.

The child process first reports a message that it is running then sleeps for two seconds. It then awakes, reports a message and calls sys.exit() with an exitcode of 1.

The child process terminates and the main process wakes up.

The status of the child process is reported indicating that it is no longer running (as expected) and that the exit code was 1, as we set when we called sys.exit().

This highlights how a child process may terminate itself and how the parent process may check the exitcode of a child process.

Exit the Main Process With a Child Process

Calling sys.exit() in a parent process will not terminate the process if it has one or more running child processes.

We can explore this with a worked example.

In this example, we will first start a child process and have it block for a moment then check the running status and exit code of the parent process. The parent process will start the child process, block for a moment then attempt to terminate with a call to sys.exit(). The child process will continue running and will show that indeed the parent process is still alive, even after its call to sys.exit().

First, we can define a target task function.

The function will first report a message to indicate that it is running. It will then block for a few seconds to give time for the parent process to “exit“. It will then wake-up and get access to the multiprocessing.Process instance for the parent process via the multiprocessing.parent_process() function. Finally, the running status and exitcode of the parent process will be reported.

The task() function below implements this.

Источник

Читайте также:  Html для любого разрешения экрана
Оцените статью