Print exit code python

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

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.

for val in range(0,5): if val == 3: print(quit) quit() print(val)

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.

Python quit() function

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

for val in range(0,5): if val == 3: print(exit) exit() print(val)

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 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.

import sys marks = 12 if marks < 20: sys.exit("Marks is less than 20") else: print("Marks is not less than 20")

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 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.

import os for i in range(5): if i == 3: print(exit) os._exit(0) print(i)

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 os.exit() function

Python raise SystemExit

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

for i in range(8): if i == 5: print(exit) raise SystemExit print(i)

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.

Читайте также:  Php convert any file to pdf

You can refer to the below screenshot python raise SystemExit.

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.

import sys my_list = [] if len(my_list) < 5: sys.exit('list length is less than 5')

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.

python exit command

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.

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

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

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?

Читайте также:  Configparser for python 3

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.

Источник

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?

Читайте также:  All html commands pdf

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

Источник

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