Python windows exit program

Как выйти из программы в Python 3

Как выйти из программы в Python 3 при помощи разных самых простых команд, методов, функций, операторов. Как корректно завершить работу программы и избежать различных ошибок?

Версия Python 3.5

Стандартный способ завершения программы в Python

Для этого варианта первую строчку ниже нужно прописать в самом начале файла, так как любой импорт пакетов или модулей производится только в самом начале файла. А уже в нужном месте кода для остановки и выхода из программы следует прописать вторую строчку кода. Если поискать, в интернете можно найти информацию, что данный вариант является самым оптимальным. Также программисты пишут, что данная функция лежит в стандартном модуле и поэтому всегда доступна.

Вызов sys.exit() — стандартный способ завершения программы в Python. Но это не так, если не подключить модуль, она не сработает.

Функция exit() для выхода из программы в Python 3

А вот функция exit() поможет не просто прервать выполнения цикла, но и полностью останавливает программу, код далее не читается. В переводе с английского exit — выход. Кстати, подключать для вызова и корректной работы данной функции в Python 3.5 никакой модуль не нужно — она прекрасно работает и так.

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

Кстати, функция quit() также работает для закрытия программы на Python и не требует для своей работы подключения каких-либо модулей.

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

Python exit command (quit(), exit(), sys.exit())

In this python tutorial, you will learn about the Python exit command with a few examples. Here we will check:

  • Python quit() function
  • Python exit() function
  • Python sys.exit() function
  • Python os.exit() function
  • Python raise SystemExit
  • Program to stop code execution in python
  • Difference between exit() and sys.exit() in python

Python exit command

Let us check out the exit commands in python like quit(), exit(), sys.exit() commands.

Python quit() function

In python, we have an in-built quit() function which is used to exit a python program. When it encounters the quit() function in the system, it terminates the execution of the program completely.

It should not be used in production code and this function should only be used in the interpreter.

Example:

After writing the above code (python quit() function), Ones you will print “ val ” then the output will appear as a “ 0 1 2 “. Here, if the value of “val” becomes “3” then the program is forced to quit, and it will print the quit message.

You can refer to the below screenshot python quit() function.

Читайте также:  Как перезапустить буфер обмена windows 10

Python exit() function

We can also use the in-built exit() function in python to exit and come out of the program in python. It should be used in the interpreter only, it is like a synonym of quit() to make python more user-friendly

Example:

After writing the above code (python exit() function), Ones you will print “ val ” then the output will appear as a “ 0 1 2 “. Here, if the value of “val” becomes “3” then the program is forced to exit, and it will print the exit message too.

You can refer to the below screenshot python exit() function.

Python sys.exit() function

In python, sys.exit() is considered good to be used in production code unlike quit() and exit() as sys module is always available. It also contains the in-built function to exit the program and come out of the execution process. The sys.exit() also raises the SystemExit exception.

Example:

After writing the above code (python sys.exit() function), the output will appear as a “ Marks is less than 20 “. Here, if the marks are less than 20 then it will exit the program as an exception occurred and it will print SystemExit with the argument.

You can refer to the below screenshot python sys.exit() function.

Python os.exit() function

So first, we will import os module. Then, the os.exit() method is used to terminate the process with the specified status. We can use this method without flushing buffers or calling any cleanup handlers.

Example:

After writing the above code (python os.exit() function), the output will appear as a “ 0 1 2 “. Here, it will exit the program, if the value of ‘i’ equal to 3 then it will print the exit message.

You can refer to the below screenshot python os.exit() function.

Python raise SystemExit

The SystemExit is an exception which is raised, when the program is running needs to be stop.

Example:

After writing the above code (python raise SystemExit), the output will appear as “ 0 1 2 3 4 “. Here, we will use this exception to raise an error. If the value of ‘i’ equal to 5 then, it will exit the program and print the exit message.

You can refer to the below screenshot python raise SystemExit.

Program to stop code execution in python

To stop code execution in python first, we have to import the sys object, and then we can call the exit() function to stop the program from running. It is the most reliable way for stopping code execution. We can also pass the string to the Python exit() method.

Example:

After writing the above code (program to stop code execution in python), the output will appear as a “ list length is less than 5 “. If you want to prevent it from running, if a certain condition is not met then you can stop the execution. Here, the length of “my_list” is less than 5 so it stops the execution.

You can refer to the below screenshot program to stop code execution in python.

Difference between exit() and sys.exit() in python

  • exit() – If we use exit() in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. The exit() is considered bad to use in production code because it relies on site module.
  • sys.exit() – But sys.exit() is better in this case because it closes the program and doesn’t ask. It is considered good to use in production code because the sys module will always be there.
Читайте также:  Не устанавливается itunes ошибка windows installer

In this Python tutorial, we learned about the python exit command with example and also we have seen how to use it like:

  • Python quit() function
  • Python exit() function
  • Python sys.exit() function
  • Python os.exit() function
  • Python raise SystemExit
  • Program to stop code execution in python
  • Difference between exit() and sys.exit() in python

Entrepreneur, Founder, Author, Blogger, Trainer, and more. Check out my profile.

how to detect program exited in python on windows and do something on exit

I want to do something when terminate the python script on windows.

Please check my sample code. It has a problem. when I press CTRL+C or Close the cmd window.on_exit() will not be executed.and windows popup «python.exe has stopped working, windows is checking the solution to the problem «

Thanks in advance and sorry for poor english.

2 Answers 2

As @mata suggests, you should use the atexit module to register a function to be called when the script exits normally, i.e. not via an unhandled Windows exception, ExitProcess , or TerminateProcess .

If you need to use SetConsoleCtrlHandler for some other reason, keep a reference to the callback to prevent it from being garbage collected. Otherwise the process will crash (at best).

You’d also want an unset_console_ctrl_handler function.

FYI, the console isn’t a «cmd» window. cmd.exe is a console user interface (CUI) program that’s typically the %COMSPEC% command interpreter. In this respect it’s no different from powershell.exe or python.exe, or any other console application.

A console window implements a character interface that’s compatible with traditional standard I/O using StandardInput , StandardOutput , and StandardError . There’s also a functional API (as opposed to terminal control sequences) to create more elaborate text interfaces. Each UCS-2 character in the console buffer has attributes such as color and intensity.

Завершение программы в Python

Как сделать раннее завершение программы в Python? В самоучителе я нашёл несколько примеров:

Однако там не было объяснения какой метод лучше. Какой метод является наиболее «безаварийным»?

И заодно: есть ли в Python понятие Autocloseable объектов? Если я сделаю ранее завершение программы, нужно ли мне будет закрывать файлы и т.д.?

2 ответа 2

Короткий ответ:
Лучше использовать sys.exit()

Механизм завершения процесса в Python реализован через бросание исключения SystemExit , таким образом можно просто создать подобное исключение и программа завершится:

Функция exit и аналогичная ей quit созданы для удобства работы в интерактивном режиме и их не рекомендуется использовать внутри скриптов:

They are useful for the interactive interpreter shell and should not be used in programs.

По факту они также просто поднимают исключение, и при попытке вызова без скобок напишут подсказку о правильном способе выхода из интерпретатора:

Использовать sys.exit стоит потому, что эта функция лежит в стандартном модуле и будет всегда там доступна. Также это довольно явный способ выразить своё желание завершить программу.

Есть также дополнительный метод для немедленного завершения программы: os._exit . У него довольно специфическая область применения, и там же есть замечание:

The standard way to exit is sys.exit(n)

Т.е. здесь даётся подтверждение того, что стандартный способ завершения программы — это вызов sys.exit .

Функция os.abort , упомянутая вами, использует механизм сигналов процессу. Конкретно при вызове этой функции будет передан сигнал SIGABRT , что в linux приведёт к завершению программы и созданию дампа памяти процесса. Подобное завершение рассматривается операционной системой как аварийное, поэтому не стоит использовать его для безаварийного завершения приложения.

Читайте также:  Как установить драйвер аудиоконтроллера windows

По второй части вопроса. В Python есть развитая система контекстных менеджеров: классов, которые умеют работать с оператором with . Самое частое использование этого механизма встречается, вероятно, с файлами.

Этот код откроет файл, напечатает его содержимое на экран и закроет файл автоматически, даже если возникнет исключение при его печати.

Для классов, которые не приспособлены для работы с with есть функция closing в библиотеке contextlib . Из документации:

is equivalent to this:

Вот небольшой пример работы этой функции:

Теперь небольшое отступление о том, почему стоит использовать конструкцию with .

Известно, что программа завершится от любого необработанного исключения, а не только от SystemExit . Таким образом, если в вашем коде используются какие-то ресурсы, которые требуется правильным образом закрывать перед завершением работы, нужно оборачивать работу с ними в блоки try . finally . .

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

Так как выход из программы — это всего лишь брошенное исключение, то и в случае использования функции sys.exit закрытие открытых в операторе with ресурсов произойдёт корректно:

Вы можете писать также и свои классы, предоставляющие ресурсы или классы, оборачивающие другие, которые нужно уметь закрывать автоматически. Для этого используются методы __enter__ и __exit__ .

Exit a Python Program in 3 Easy Ways!

Hey, all. In this article, we will be having a look at some functions that can be considered as handy to perform this task — Exit a Python program.

Technique 1: Using quit() function

The in-built quit() function offered by the Python functions, can be used to exit a Python program.

Syntax:

As soon as the system encounters the quit() function, it terminates the execution of the program completely.

Example:

As seen above, after the first iteration of the for loop, the interpreter encounters the quit() function and terminates the program.

Output:

Technique 2: Python sys.exit() function

Python sys module contains an in-built function to exit the program and come out of the execution process — sys.exit() function.

The sys.exit() function can be used at any point of time without having to worry about the corruption in the code.

Syntax:

Let us have a look at the below example to understand sys.exit() function.

Example:

Output:

Technique 3: Using exit() function

Apart from the above mentioned techniques, we can use the in-built exit() function to quit and come out of the execution loop of the program in Python.

Syntax:

Example:

The exit() function can be considered as an alternative to the quit() function, which enables us to terminate the execution of the program.

Output:

Conclusion

By this, we have come to the end of this topic. The exit() and quit() functions cannot be used in the operational and production codes. Because, these two functions can be implemented only if the site module is imported.

Thus, out of the above mentioned methods, the most preferred method is sys.exit() method.

Feel free to comment below, in case you come across any question.

Till then, Happy Learning!!

References

Pascal’s Triangle using Python

Add a newline character in Python — 6 Easy Ways!

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