4 Способа выхода из программы с помощью функции Python Exit
Есть много случаев, когда мы хотим выйти из программы до того, как это сделает интерпретатор, и для этой цели у нас есть python exit function. Помимо exit у нас также есть некоторые функции, такие как quit (), sys.exit() и os._exit(). Давайте узнаем о каждом из их достоинств и недостатков.
Во время простого выполнения программы (без использования упомянутых выше функций), когда интерпретатор достигает конца программы/скрипта, он выходит из программы. Но когда мы используем такие функции, как выход и выход, он выходит автоматически в это время.
Работа с функциями выхода Python
Иногда нам нужно, чтобы программа остановилась до того, как интерпретатор достигнет конца сценария, например, если мы сталкиваемся с чем-то, что не требуется. Итак, давайте разберемся, какие функции можно использовать ниже 4 способами –
- Python Exit()
- quit()
- Функция Sys.exit ()
- os._exit Функция
1. Выход Python()
Эта функция может быть реализована только тогда, когда site.py модуль есть (он поставляется с предустановленным Python), и именно поэтому его не следует использовать в производственной среде. Он должен использоваться только с переводчиком.
В фоновом режиме функция выхода python использует исключение SystemExit. Это означает, что когда интерпретатор сталкивается с exit (), он выдает исключение SystemExit. Кроме того, он не печатает трассировку стека, что означает, почему произошла ошибка.
Если мы выполним print(exit) –
Ниже приведен код выхода из программы, если мы сталкиваемся с избирателем в возрасте до 18 лет.
Если мы запустим программу на python, то на выходе получим-
2. Python exit с помощью quit()
Эта функция работает точно так же, как exit(). Нет никакой разницы. Это делается для того, чтобы сделать язык более удобным для пользователя. Только подумай, ты же href=”https://en.wikipedia.org/wiki/Programmer”>новичок в языке python, какая функция, по вашему мнению, должна использоваться для выхода из программы? Выходите или уходите, верно? Это то, что делает Python простым в использовании языком. Как и функция python exit, функция python quit() не оставляет следов стека и не должна использоваться в реальной жизни. href=”https://en.wikipedia.org/wiki/Programmer”>новичок в языке python, какая функция, по вашему мнению, должна использоваться для выхода из программы? Выходите или уходите, верно? Это то, что делает Python простым в использовании языком. Как и функция python exit, функция python quit() не оставляет следов стека и не должна использоваться в реальной жизни.
Предположим, мы хотим выйти из программы, когда встречаем имя в списке меток-
3. Функция Sys.exit() в Python
Эта функция полезна и может быть использована в реальном мире или производственной среде, потому что это функция модуля sys, доступного везде. Мы должны использовать эту функцию для управления терминалом, у которого есть большие файлы.
4. Функция os._exit В Python
Эта функция вызывает функцию C (), которая немедленно завершает работу программы. Кроме того, это утверждение “никогда не может вернуться”.
Разница между выходом(0) и выходом(1)
Основное различие между exit(0) и exit(1) заключается в том, что exit(0) представляет успех при любых ошибках, а exit(1) представляет неудачу.
Должен Читать:
- Как преобразовать строку в нижний регистр в
- Как вычислить Квадратный корень
- Пользовательский ввод | Функция ввода () | Ввод с клавиатуры
- Лучшая книга для изучения Python
Вывод
Функция exit является полезной функцией, когда мы хотим выйти из нашей программы без интерпретатора, достигающего конца программы. Некоторые из используемых функций-это python exit function, quit(), sys.exit(), os._exit(). Мы должны использовать эти функции в соответствии с нашими потребностями.
Попробуйте запустить программы на вашей стороне и дайте мне знать, если у вас есть какие-либо вопросы.
6 ways to exit program in Python
Python is one of the most versatile and dynamic programming languages used out there. Nowadays, It is the most used programming language, and for good reason. Python gives a programmer the option and the allowance to exit a python program whenever he/she wants.
Table of Contents
Using the quit() function
A simple and effective way to exit a program in Python is to use the in-built quit() function. No external libraries need to be imported to use the quit() function.
This function has a very simple syntax:
When the system comes up against the quit() function, it goes on and concludes the execution of the given program completely.
The quit() function can be used in a python program in the following way:
The Python interpreter encounters the quit() function after the for loop iterates once, and the program is then terminated after the first iteration.
Using the sys.exit() function
The sys module can be imported to the Python code and it provides various variables and functions that can be utilized to manipulate various pieces of the Python runtime environment.
The sys.exit() function is an in-built function contained inside the sys module and it is used to achieve the simple task of exiting the program.
It can be used at any point in time to come out of the execution process without having the need to worry about the effects it may have on a particular code.
The sys.exit() function can be used in a python program in the following way:
Using the exit() function
There exists an exit() function in python which is another alternative and it enables us to end program in Python.
It is preferable to use this in the interpreter only and is an alternative to the quit() function to make the code a little more user-friendly.
The exit() function can be used in a python program in the following way:
The two functions, exit() and quit() can only be implemented if and when the site module is imported to the python code. Therefore, these two functions cannot be used in the production and operational codes.
The sys.exit() method is the most popular and the most preferred method to terminate a program in Python.
Using the KeyboardInterrupt command
If Python program is running in cosole, then pressing CTRL + C on windows and CTRL + Z on unix will raise KeyboardInterrupt exception in the main thread.
If Python program does not catch the exception, then it will cause python program to exit. If you have except: for catching this exception, then it may prevent Python program to exit.
If KeyboardInterrupt does not work for you, then you can use SIGBREAK signal by pressing CTRL + PAUSE/BREAK on windows.
In Linux/Unix, you can find PID of Python process by following command:
and you can kill -9 to kill the python process. kill -9 <pid> will send SIGKILL and will stop the process immediately.
For example:
If PID of Python process is 6243, you can use following command:
In Windows, you can use taskkill command to end the windows process. YOu can also open task manager, find python.exe and end the process. It will exit Python program immediately.
Using the raise SystemExit command
Simply put, the raise keyword’s main function is to raise an exception. The kind of error you want to raise can be defined.
BaseException class is a base class of the SystemExit function. The SystemExit function is inherited from the BaseException such that it is able to avoid getting caught by the code that catches all exception.
The SystemExit function can be raised in the following way in Python code:
How to stop/terminate a python script from running?
New! Save questions or answers and organize your favorite content.
Learn more.
I wrote a program in IDLE to tokenize text files and it starts to tokeniza 349 text files! How can I stop it? How can I stop a running Python program?
18 Answers 18
You can also do it if you use the exit() function in your code. More ideally, you can do sys.exit() . sys.exit() which might terminate Python even if you are running things in parallel through the multiprocessing package.
Note: In order to use the sys.exit() , you must import it: import sys
To stop your program, just press Control + C .
If your program is running at an interactive console, pressing CTRL + C will raise a KeyboardInterrupt exception on the main thread.
If your Python program doesn’t catch it, the KeyboardInterrupt will cause Python to exit. However, an except KeyboardInterrupt: block, or something like a bare except: , will prevent this mechanism from actually stopping the script from running.
Sometimes if KeyboardInterrupt is not working you can send a SIGBREAK signal instead; on Windows, CTRL + Pause/Break may be handled by the interpreter without generating a catchable KeyboardInterrupt exception.
However, these mechanisms mainly only work if the Python interpreter is running and responding to operating system events. If the Python interpreter is not responding for some reason, the most effective way is to terminate the entire operating system process that is running the interpreter. The mechanism for this varies by operating system.
In a Unix-style shell environment, you can press CTRL + Z to suspend whatever process is currently controlling the console. Once you get the shell prompt back, you can use jobs to list suspended jobs, and you can kill the first suspended job with kill %1 . (If you want to start it running again, you can continue the job in the foreground by using fg %1 ; read your shell’s manual on job control for more information.)
Alternatively, in a Unix or Unix-like environment, you can find the Python process’s PID (process identifier) and kill it by PID. Use something like ps aux | grep python to find which Python processes are running, and then use kill <pid> to send a SIGTERM signal.
The kill command on Unix sends SIGTERM by default, and a Python program can install a signal handler for SIGTERM using the signal module. In theory, any signal handler for SIGTERM should shut down the process gracefully. But sometimes if the process is stuck (for example, blocked in an uninterruptable IO sleep state), a SIGTERM signal has no effect because the process can’t even wake up to handle it.
To forcibly kill a process that isn’t responding to signals, you need to send the SIGKILL signal, sometimes referred to as kill -9 because 9 is the numeric value of the SIGKILL constant. From the command line, you can use kill -KILL <pid> (or kill -9 <pid> for short) to send a SIGKILL and stop the process running immediately.