Python exit main program

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.

Читайте также:  Fingerprint code in java

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.

Читайте также:  Atx aerocool python обзор

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.

Источник

Как использовать функцию exit в скриптах Python

Функция exit в Python позволяет в любой момент остановить выполнение скрипта или программы. Это может понадобиться для обработки ошибок, тестирования и отладки, остановки программы при соблюдении каких-то условий.

Необязательный аргумент status представляет собой статус выхода. Это целочисленное значение, которое указывает на причину завершения программы. Принято считать, что статус 0 означает успешное выполнение, а любой ненулевой статус указывает на ошибку или ненормальное завершение.

Если аргумент status не указан, используется значение по умолчанию 0.

Вот пример использования функции exit в Python:

print("Before exit") exit(1) print("After exit") # This line will not be executed

В этом примере программа выводит строку «Before exit». Но когда exit() вызывается с аргументом 1, программа немедленно завершается, не выполняя оставшийся код. Поэтому строка «After exit» не выводится.

От редакции Pythonist: также предлагаем почитать статьи «Как запустить скрипт Python» и «Создание Python-скрипта, выполняемого в Unix».

Как использовать функцию exit() в Python

Давайте напишем скрипт на Python и используем в нем функцию exit.

import sys def main(): try: print("Welcome to the program!") # Check for termination condition user_input = input("Do you want to exit the program? (y/n): ") if user_input.lower() == "y": exit_program() # Continue with other operations except Exception as e: print(f"An error occurred: ") exit_program() def exit_program(): print("Exiting the program. ") sys.exit(0) if __name__ == "__main__": main()

Пояснение кода

  1. Скрипт начинается с импорта модуля sys, который предоставляет доступ к функции exit() .
  2. Функция main() служит точкой входа в программу. Внутри этой функции можно добавлять свой код.
  3. Внутри функции main() можно выполнять различные операции. В данном примере мы просто выводим приветственное сообщение и спрашиваем пользователя, хочет ли он выйти.
  4. После получения пользовательского ввода мы проверяем, хочет ли пользователь выйти. Для этого сравниваем его ввод с «y» (без учета регистра). Если условие истинно, вызываем функцию exit_program() для завершения работы скрипта.
  5. Функция exit_program() выводит сообщение о том, что программа завершается, а затем вызывает sys.exit(0) для завершения программы. Аргумент 0, переданный в sys.exit() , означает успешное завершение программы. При необходимости вы можете выбрать другой код завершения.
  6. Наконец, при помощи переменной __name__ проверяем, выполняется ли скрипт как главный модуль. Если это так, вызываем функцию main() для запуска программы.
Читайте также:  Django and python ide

Best practices использования функции exit в Python

Импортируйте модуль sys

Чтобы использовать функцию exit(), необходимо импортировать модуль sys в начале скрипта. Включите в свой код следующую строку:

Определите условие выхода

Определите условие или ситуацию, в которой вы хотите завершить работу программы. Оно может быть основано на вводе пользователя, определенном событии, состоянии ошибки или любых других критериях, требующих остановки программы.

Используйте sys.exit() для завершения программы

Если условие завершения истинно, вызовите функцию sys.exit() , чтобы остановить выполнение программы. В качестве аргумента ей можно передать необязательный код состояния выхода, указывающий на причину завершения.

Опять же, код состояния 0 обычно используется для обозначения успешного завершения программы, в то время как ненулевые значения представляют различные типы ошибок или исключительных условий.

if condition_met: sys.exit() # Terminate the program with status code 0

Вы также можете передать код состояния для предоставления дополнительной информации:

if error_occurred: sys.exit(1) # Terminate the program with status code 1 indicating an error

Очистка ресурсов (опционально)

Допустим, ваша программа использует ресурсы, которые должны быть надлежащим образом освобождены перед завершением. Примеры — закрытие файлов или освобождение сетевых соединений. В таком случае перед вызовом sys.exit() можно включить код очистки. Это гарантирует, что ресурсы будут обработаны должным образом, даже если программа завершится неожиданно.

Документируйте условия выхода

Важно документировать конкретные условия завершения в коде и оставлять комментарии, указывающие, почему программа завершается. Это поможет другим разработчикам понять цель и поведение вызовов exit() .

Заключение

Теперь вы знаете, как использовать функцию exit в Python для завершения выполнения программы. По желанию можно передать в эту функцию в качестве аргумента код состояния, предоставляя дополнительную информацию о причине завершения.

Соблюдая правила, приведенные в этой статье, вы сможете эффективно использовать exit() для остановки программы в случае необходимости.

Очень важно проявлять осторожность и применять эту функцию разумно. Она должна использоваться только в соответствующих обстоятельствах, когда вы хотите принудительно остановить выполнение вашего скрипта Python при определенных условиях или когда вам нужно завершить программу немедленно.

Источник

Оцените статью