Exit python shell windows

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.

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.

Читайте также:  Проверить пробег фотоаппарата mac os

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.

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.

Python to close own CMD shell window on exit

I am running multiple processes (hundreds), each of which is in python and invoked using:

where the /k leaves the cmd window open after execution. This is good to inspect for errors. However, as I call hundreds of jobs, my screen gets cluttered.

How then to make python close its own host cmd window on successful completion only? I need the errored jobs to remain visible.

2 Answers 2

Let us first analyze what the two posted Python script lines really do on execution of the Python script. Thanks goes to eryksun for his deep investigation really using Python resulting in a correct description as it can be read below now.

os.system() results in execution of cmd.exe /C in foreground with a console window and halts execution of the Python script until Windows command interpreter terminates. If the Python script itself is executed in a console, the started cmd.exe inherits this console.

This command process starts with start , an internal command of cmd.exe , one more command process with a foreground console window. Fine, but this second command process terminates immediately on finishing execution of the command. That is not so good if you want to see errors output by the executed script or by Python interpreter itself on running the Python script.

So the second command process starts cmd.exe with option /k to keep running this command process inheriting the console created by start and the console window opened after finishing the execution of the specified command.

The second command process runs internal command call which is not necessary at all because python is in real python.exe , a console application and not a batch file. Therefore call is not needed at all.

It is advisable to always specify applications and scripts with complete name of file, i.e. file name + file extension and not just file name only. If the path to executable/script is known and fixed, it should be specified too. This makes the execution of the application/script independent on what is the current directory and the environment variables PATHEXT and PATH .

Python interpreter executes the specified Python script in second console.

The first command process started with os.system() terminates immediately after start finished which occurs already after starting cmd.exe /k while python.exe is interpreting the Python script.

So remaining is the second command process running the Python interpreter with the script. This command process keeps running even after Python interpreter terminated after finishing execution of specified Python script.

So the goal is to terminate also the second command process with the console window once Python interpreter finished the execution of the Python script, but only if no error occurred on execution of the script.

Well, I don’t have Python installed at all, but I suppose it exits with a return code greater 0 on an error on execution of a script. Otherwise the exit code is 0 on successful execution of the script.

Читайте также:  Горячие клавиши mac os вырезать файл

So it might work to use a command like this:

The command line to execute by second command process started with start cmd.exe /K contains two commands now:

  1. Python interpreter python.exe with the script to execute as parameter
    and
  2. the internal command exit whereby this second command should be executed by Windows command interpreter only if exit code of first command is 0 because of operator && .

See the answer on Single line with multiple commands using Windows batch file for details about single command line with more than one command to execute.

Each ampersand must be escaped here with escape character of Windows command interpreter which is the caret character ^ . This is necessary as otherwise && would be interpreted by first command process running start as additional command to run after successful execution of start .

Please note that I don’t have Python installed and therefore made just following test from within a command prompt window using a batch file Test.bat with the single command line @echo %

dp0 executed. & exit /B 1 .

Test.bat is a batch file and not an executable which requires the usage of command call . The started command process with no specific window title keeps open because Test.bat exits with return code 1. The started command process exits itself if I modify in Test.bat the number 1 to 0 at end of the command line.

Of course it is necessary that the script code itself halts script execution on an error detected by the script code on using this solution.

Exiting from python Command Line

To exit from Python command line, I have to type exit(). If I type exit, it says

Usually when you type exit , you would want to exit the program. Why does the interpreter give me the above error when it knows I am trying to exit the command line? Why doesn’t it just exit? I know it doesn’t matter and its a silly question but I am curious.

11 Answers 11

In my python interpreter exit is actually a string and not a function — ‘Use Ctrl-D (i.e. EOF) to exit.’ . You can check on your interpreter by entering type(exit)

In active python what is happening is that exit is a function. If you do not call the function it will print out the string representation of the object. This is the default behaviour for any object returned. It’s just that the designers thought people might try to type exit to exit the interpreter, so they made the string representation of the exit function a helpful message. You can check this behaviour by typing str(exit) or even print exit .

This works for me, best way to come out of python prompt.

When you type exit in the command line, it finds the variable with that name and calls __repr__ (or __str__ ) on it. Usually, you’d get a result like:

But they decided to redefine that function for the exit object to display a helpful message instead. Whether or not that’s a stupid behavior or not, is a subjective question, but one possible reason why it doesn’t «just exit» is:

Suppose you’re looking at some code in a debugger, for instance, and one of the objects references the exit function. When the debugger tries to call __repr__ on that object to display that function to you, the program suddenly stops! That would be really unexpected, and the measures to counter that might complicate things further (for instance, even if you limit that behavior to the command line, what if you try to print some object that have exit as an attribute?)

How to stop Python closing immediately when executed in Microsoft Windows

I have just started college and we are going to be using python. We really have done nothing so I have downloaded the program and done some print commands, and that’s it.

When I run my .py file (a print command) it immediately closes after appearing. I understand why it does this — it’s given the output, so it’s done what it needs to do — but I also understand that you can stop this from happening.

I looked around this website and none of the solutions given to this question worked, either that or I didn’t understand them.

Читайте также:  Windows 10 забыл пароль при входе что делать

Is there a simple command I can input to my IDLE editor that will put the program on hold or something? I have tried input(«prompt: «) as suggested by someone, and that made no difference.

If there isn’t a command for this, is there a way to change the settings on the computer so that programs don’t auto close?

16 Answers 16

In Python 3, add the following to the end of your code:

This will cause the program to wait for user input, with pressing ENTER causing the program to finish.

You can double click on your script.py file in Windows conveniently this way.

The only thing that worked for me -i command line argument.

Just put all your python code inside a .py file and then run the following command;

It means that if you set -i variable and run your module then python doesn’t exit on SystemExit. Read more at the this link.

Open your cmd (command prompt) and run Python commmands from there. (on Windows go to run or search and type cmd) It should look like this:

This will execute your code in cmd and it will be left open. However to use python command, Python has to be properly installed so cmd recognizes it as a command. Checkout proper installation and variable registration for your OS if this does not happen

Run the command using the windows command prompt from your main Python library source. Example.

at the end to have it stop.

If you just want a delay

Depending on what I’m using it for, or if I’m doing something that others will use, I typically just input(«Do eighteen backflips to continue») if it’s just for me, if others will be using I just create a batch file and pause it after

I use the above if there is going to be files renamed, moved, copied, etc. and my cmd needs to be in the particular folder for things to fall where I want them, otherwise — just

In Python 2.7 adding this to the end of my py file ( if __name__ == ‘__main__’: ) works:

The reason why it is closing is because the program is not running anymore, simply add any sort of loop or input to fix this (or you could just run it through idle.)

I know a simple answer! Open your cmd, the type in: cd C:\directory your file is in and then type python your progam.py

Well I got similar issue, It is solved by adding Environment Variable.

Add System Variables in Window

Your Python path.

I think I am too late to answer this question but anyways here goes nothing.

I have run in to the same problem before and I think there are two alternative solutions you can choose from.

from time import * sleep(10)

  1. using a prompt message (note that I am using python 2.7)

exit_now = raw_input(«Do you like to exit now (Y)es (N)o ? «)’

if exit_now.lower() = ‘n’

//more processing here

Alternatively you can use a hybrid of those two methods as well where you can prompt for a message and use sleep(sometime) to delay the window closing as well. choice is yours.

please note the above are just ideas and if you want to use any of those in practice you might have to think about your application logic a bit.

I couldn’t find anywhere on the internet a true non-script specific, double click and the window doesn’t close solution. I guess I’m too lazy to drag and drop or type when I don’t need to so after some experimentation I came up with a solution.

The basic idea is to reassociate .py files so they run a separate initial script before running the intended script. The initial script launches a new command prompt window with the /k parameter which keeps the command prompt open after completion and runs your intended script in the new window.

Maybe there are good reasons not to do this, those with more knowledge please comment if so, but I figure if I run into any it is easy to revert back if needed. One possibly undesirable side effect is dragging and dropping or typing and running from a command prompt now opens a second command prompt rather than running in the command prompt you dragged or typed in.

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