Как на питоне закончить программу

4 Способа выхода из программы с помощью функции Python Exit

Есть много случаев, когда мы хотим выйти из программы до того, как это сделает интерпретатор, и для этой цели у нас есть python exit function. Помимо exit у нас также есть некоторые функции, такие как quit (), sys.exit() и os._exit(). Давайте узнаем о каждом из их достоинств и недостатков.

Во время простого выполнения программы (без использования упомянутых выше функций), когда интерпретатор достигает конца программы/скрипта, он выходит из программы. Но когда мы используем такие функции, как выход и выход, он выходит автоматически в это время.

Работа с функциями выхода Python

Иногда нам нужно, чтобы программа остановилась до того, как интерпретатор достигнет конца сценария, например, если мы сталкиваемся с чем-то, что не требуется. Итак, давайте разберемся, какие функции можно использовать ниже 4 способами –

1. Выход Python()

Эта функция может быть реализована только тогда, когда site.py модуль есть (он поставляется с предустановленным Python), и именно поэтому его не следует использовать в производственной среде. Он должен использоваться только с переводчиком.

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

Если мы выполним print(exit) –

Output- Use exit() or Ctrl-Z plus Return to exit

Ниже приведен код выхода из программы, если мы сталкиваемся с избирателем в возрасте до 18 лет.

ages=[19,45,12,78] for age in ages: if age < 18: print(age,"not allowed") exit() else: print(age,"allowed")
Output- 19 allowed 45 allowed 12 not allowed

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

Предположим, мы хотим выйти из программы, когда встречаем имя в списке меток-

marks=[78,89,92,"ashwini",56] for i in marks: if type(i) : print("Oops!! Encountered a non-int value:",i) quit()
Output- Oops!! Encountered a non-int value: ashwini

3. Функция Sys.exit() в Python

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

Output- Voting not allowed because the age is less than 18

4. Функция os._exit В Python

Эта функция вызывает функцию C (), которая немедленно завершает работу программы. Кроме того, это утверждение “никогда не может вернуться”.

Читайте также:  What is date object in javascript

Разница между выходом(0) и выходом(1)

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

Должен Читать:

  • Как преобразовать строку в нижний регистр в
  • Как вычислить Квадратный корень
  • Пользовательский ввод | Функция ввода () | Ввод с клавиатуры
  • Лучшая книга для изучения Python

Вывод

Функция exit является полезной функцией, когда мы хотим выйти из нашей программы без интерпретатора, достигающего конца программы. Некоторые из используемых функций-это python exit function, quit(), sys.exit(), os._exit(). Мы должны использовать эти функции в соответствии с нашими потребностями.

Попробуйте запустить программы на вашей стороне и дайте мне знать, если у вас есть какие-либо вопросы.

Читайте ещё по теме:

Источник

How Do You End Scripts in Python?

Programming means giving instructions to a computer on how to perform a task. These instructions are written using a programming language. An organized sequence of such instructions is called a script.

As a programmer, your main job is to write scripts (i.e. programs). However, you also need to know how scripts can end. In this article, we will go over different ways a Python script can end. There is no prerequisite knowledge for this article, but it is better if you are familiar with basic Python terms.

If you are new to programming or plan to start learning it, Python is the best way to start your programming adventure. It is an easy and intuitive language, and the code is as understandable as plain English.

Scripts are written to perform a task; they are supposed to end after the task is completed. If a script never ends, we have a serious problem. For instance, if there is an infinite while loop in the script, the code theoretically never ends and might require an external interruption.

It is important to note that an infinite while loop might be created on purpose. A script can be written to create a service that is supposed to run forever. In this case, the infinite loop is intentional and there is no problem with that.

The end of a Python script can be frustrating or satisfying, depending on the result. If the script does what it is supposed to do, then it’s awesome. On the other hand, if it ends by raising an exception or throwing an error, then we will not be very happy.

5 Ways to End Python Scripts

Let’s start with the most common and obvious case: a script ends when there are no more lines to execute.

1. All the Lines Are Executed

The following is a simple script that prints the names in the list, along with the number of characters they contain:

mylist = ["Jane", "John", "Ashley", "Matt"] for name in mylist: print(name, len(name))
Jane 4 John 4 Ashley 6 Matt 4

The script does its job and ends. We all are happy.

Читайте также:  Awp lego 2 bsp css

Python scripts, or scripts in any other programming language, can perform a wide range of operations. In many cases, we cannot visually check the results. For instance, the job of a script might be reading data from a database, doing a set of transformations, and writing the transformed data to another database.

In scripts that perform a series of operations, it’s a good practice to keep a log file or add print statements after each individual task. It lets us do simple debugging in case of a problem. We can also check the log file or read the output of print statements to make sure the operation was completed successfully.

2. Uncaught Exception

It usually takes several iterations to write a script that runs without an error; it’s rare to get it right the first time. Thus, a common way that a script ends is an uncaught exception; this means there is an error in the script.

When writing scripts, we can think of some possible issues and place try-except blocks in the script to handle them. These are the exceptions that we are able to catch. The other ones can be considered uncaught exceptions.

Consider the following code:

mylist = ["Jane", "John", 2, "Max"] for i in mylist: print(f"The length of is ")
The length of Jane is 4 The length of John is 4 Traceback (most recent call last): File "", line 4, in TypeError: object of type 'int' has no len()

The code prints the length of each item in the list. It executes without a problem until the third item, which is an integer. Since we cannot apply the len function to an integer, the script throws an error and ends.

We can make the script continue by adding a try-except block.

mylist = ["Jane", "John", 2, "Max"] for i in mylist: try: print(f"The length of is ") except TypeError: print(f" does not have a length!")
The length of Jane is 4 The length of John is 4 2 does not have a length! The length of Max is 3

What does this try-except block do?

  • It prints the f-string that includes the values and their lengths.
  • If the execution in the try block returns a TypeError, it is caught in the except block.
  • The script continues the execution.

The script still ends, but without an error. This case is an example of what we explained in the first section.

3. sys.exit()

The sys module is part of the Python standard library. It provides system-specific parameters and functions.

One of the functions in the sys module is exit , which simply exits Python. Although the exit behavior is the same, the output might be slightly different depending on the environment. For instance, the following block of code is executed in the PyCharm IDE:

import sys number = 29 if number < 30: sys.exit() else: print(number)
Process finished with exit code 0

Now, let’s run the same code in Jupyter Notebook:

import sys number = 29 if number < 30: sys.exit() else: print(number)
An exception has occurred, use %tb to see the full traceback. SystemExit

The sys.exit function accepts an optional argument that can be used to output an error message. The default value is 0, which indicates successful termination; any nonzero value is an abnormal termination.

Читайте также:  Web design css background

We can also pass a non-integer object as the optional argument:

import sys number = 29 if number < 30: sys.exit("The number is less than 30.") else: print(number)
An exception has occurred, use %tb to see the full traceback. SystemExit: The number is less than 30.

The sys.exit() function raises the SystemExit exception, so the cleanup functions used in the final clause of a try-except-finally block will work. In other words, we can catch the exception and handle the necessary cleanup operations or tasks.

4. exit() and quit()

The exit() and quit() functions are built into Python for terminating a script. They can be used interchangeably.

The following script prints the integers in the range from 0 to 10. If the value becomes 3, it exits Python:

for i in range(10): print(i) if i == 4: exit()
0 1 2 3 Process finished with exit code 0

Note: The exit() function also raises an exception, but it is not intercepted (unlike sys.exit() ). Therefore, it is better to use the sys.exit() function in production code to terminate Python scripts.

5. External Interruption

Another way to terminate a Python script is to interrupt it manually using the keyboard. Ctrl + C on Windows can be used to terminate Python scripts and Ctrl + Z on Unix will suspend (freeze) the execution of Python scripts.

If you press CTRL + C while a script is running in the console, the script ends and raises an exception.

Traceback (most recent call last): File "", line 2, in KeyboardInterrupt

We can implement a try-except block in the script to do a system exit in case of a KeyboardInterrupt exception. Consider the following script that prints the integers in the given range.

for i in range(1000000): print(i)

We may want to exit Python if the script is terminated by using Ctrl + C while its running. The following block of code catches the KeyboardInterrupt exception and performs a system exit.

for i in range(1000000): try: print(i) except KeyboardInterrupt: print("Program terminated manually!") raise SystemExit
Program terminated manually! Process finished with exit code 0

We have covered 5 different ways a Python script can end. They all are quite simple and easy to implement.

Python is one of the most preferred programming languages. Start your Python journey with our beginner-friendly Learn Programming with Python track. It consists of 5 interactive Python courses that gradually increase in complexity. Plus, it’s all interactive; our online console lets you instantly test everything you learn. It is a great way to practice and it makes learning more fun.

What's more, you don't need to install or set anything up on your computer. You only need to be willing to learn; we'll take care of the rest. Wait no more – start learning Python today!

Источник

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