Python sys exit error codes

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 в скриптах 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() для запуска программы.

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 при определенных условиях или когда вам нужно завершить программу немедленно.

Источник

Python Exit Codes

If you have ever worked on a Unix system, you are probably familiar with the concept of an exit code. If you are not, let’s do a quick recap. An exit code refers to a specific exit code returned by a command, script, or program upon execution. A unique code is used to indicate the status of the process after it has completed execution. The status of the process could be successful, failure, or other condition. Therefore, the role of exit codes is to indicate how the process behaved.

With that out of the way, let us explore Python exit codes, how they work, and how you can use them in your programs.

Python Standard Exit Codes

Python has only two standard codes, i.e., a one and a zero. The exit code of 0 means that the process has been executed and exited successfully. This means no error was encountered. On the other hand, an error code of 1 indicates that the process exited with a failure. Let us take a look at a very simple program that just prints the string “Welcome to linuxhint!”.

As you can guess, if we run the program above, it will execute successfully.

We can see that the program does return the desired output. On Unix systems, we can use the echo command followed by the environment variable ?. This environment variable allows you to get the exit code of the last executed command.

In our case, the last command is the Python program:

Notice that the command above returns 0. This shows that our Python program executes successfully.

Have you ever customized your shell, and it returns a red symbol if the previous command fails? Yes, it uses the exit code to do this.

Now let’s take another example:

Notice something wrong with the program above?

In the above example, the code above is missing the closing bracket for the print function. Hence, if we run the program above, it will fail and return an error.

File «/Users/username/exit_codes.py» , line 2

SyntaxError : unexpected EOF while parsing

Here, we can clearly see that the program fails and returns an error.

Let’s now check the exit code.

You guessed it; the command returns an exit code 1. This shows that the previous program failed miserably.

Python Custom Exit Codes – The SYS Module

One of the most useful modules that I encourage fellow Python geeks to learn is the SYS module.

It is a great module that is built-in Python’s standard library but provides exceptional system functionalities.

Enough praises; we can use one of the functions from the SYS module to create custom exit codes in our Python programs.

The function is called exit() and has syntax as the one shown below:

As you can tell, the function has a relatively simple syntax.

It allows you to specify the arg parameter, which is optional. It can be an integer or any supported object.

If the provided argument is an integer zero or None, it is considered a successful execution. For any other value above zero, it indicates abnormal termination.

Although it will depend on the system, the value of the exit code can range from 0 -127.

You can also pass a string which will be displayed when the program exits.

Take the example program below that returns an exit code of 125.

print ( «Welcome to linuxhint» )

In the example program above, we start by importing the exit function from the sys module.

We then use the print statement to print some text on the screen.

For the important part, we use the exit function and pass the exit code as 125.

NOTE: As soon as Python encounters the exit() function, it will immediately terminate the program and return the exit code or message specified.

We can verify this by running the program as:

We can see from the above output that the second print statement does not execute.

Let’s check the exit code as:

We can see that the exit code is 125, as specified in our program.

Consider the example below that prints a string instead of an exit code.

exit ( «Program terminated unexpectedly» )

print ( «Welcome to linuxhint» )

In this case, we are using a string literal as the arg parameter inside the function. Once we run the program:

Program terminated unexpectedly

We can see that the program prints the message before the exit function and the one in the exit function.

Can you guess what the exit code of the program above is? Let’s see:

Yes, it’s one. Any abnormal terminations of the program that do not provide their own custom codes will be assigned an exit code of 1.

NOTE: Use the exit function when you need to terminate your program immediately.

Conclusion

And with that, we have come to the end of our tutorial. In this article, we learned how Python exit codes work and how to create custom exit codes using the sys module.

Happy coding, and as always, Thanks for reading!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list

Источник

Читайте также:  Python вырезать часть строки между символами
Оцените статью