How to stop a program in Idle, python 3.2 - python

I made a program in Idle that says:
for trial in range(3):
if input('Password:') == 'password':
break
else:
# didn't find password after 3 attempts
**I need a stop program here**
print ("Welcome in")
Remember, this is in Idle, so I need program for Idle, not CMD. I also am using Python 3.2, if that helps.

A much nicer way to do this IMHO would be to put your program into a function and return when you want it to stop. Then just call the function to run your program.
def main():
for trial in range(3):
if input('Password:') == 'password':
break
else:
return
print ("Welcome in")
main()

use sys.exit() or raise SystemExit
import sys
for trial in range(3):
if input('Password:') == 'password':
break
else:
sys.exit()
print ("Welcome in"))
Edit:
To end it silently wrap it in a try-except block:
try:
import sys
for trial in range(1):
if raw_input('Password:') == 'password':
break
else:
raise SystemExit #or just sys.exit()
print ("Welcome in")
except SystemExit:
pass #when the program throws SysExit do nothing here,i.e end silently

I'm unsure what you mean by "in IDLE" vs "in CMD". A Python shell launched by IDLE should be able to be terminated the same way as a Python shell launched from the commandline.
Also, the tabs in your example appear to be wrong: everything below for... and above print... should be indented.
On to your question: are you asking for a command that terminates your script at that point? If so, adding the two lines from sys import exit and then calling exit() should do the trick, though it will raise a SystemExit exception. If you don't like that, you can add a pass handler for the SystemExit exception type at the outer layer of your program.

sys.exit can exit a program at any time.

I tried sys.exit() and it highlights 'sys' as INVALID SYNTAX.
It might be something to do with how I'm doing it, but if that's the case, then IDK then.

Related

How to terminate/killall a program in python

The first simple answer to the Linux equivalent killall(ProgramName)
The program is to be a toggle program. I can launch Firefox/program.
def tolaunch(program):
os.system("firefox")
When launched I wish to save the name of program launched, in array(simple to do), then launch the program(Firefox)/program.
Here the idea off the toggle come’s in, when Launched and I have finished my browsing, I wish to call the same program(mine), check the array for said program and exit Firefox/program, by running a simple command like killall(“Firefox”) but in Python code. I don’t want to write a long winded command/script, that first has to workout the ‘pid’.
I seem very close to the answer but cant find it.
Edit: people asked for code example | here is my code
# Toggler for macro key -|- many keys = one toggler program
import os
import sys
def startp(program):
# hard-coded
os.system("firefox")
def exitp(program):
# os.close(program)
sys.exit(program)
# Begin
# hard-coded : program start
startp("Firefox")
# loop while program/s active
# exitp("Firefox")
# exit(program) or program end
I tried to include some explanations in way off comments
What you are looking for is the sys.exit() command.
There are 4 functions that exit a program. These are the quit(), exit(), sys.exit() and os._exit(). They have almost same functionality thanks to the fact that they raise the SystemExit exception by which the Python interpreter exits and no stack traceback is printed on the screen.
Among the above four exit functions, sys.exit() is mostly preferred because the exit() and quit() functions cannot be used in production code while os._exit() is for special cases only when an immediate exit is required.
To demonstrate this behavior using the sys.exit() function:
import sys
i=0
while i in range(10):
i += 1
print(i)
if i == 5:
print('I will now exit')
sys.exit()
elif i > 5:
print('I will not run, program alredy exited :(')

How do I stop the code completely as soon as a certain thing is done?

I've already ruled out os.exit, sys.exit(), raise SystemExit(0), quit, and exit().
I want to completely stop once one of my multiple while conditions are fulfilled.
while x:
#do something
#for loop
#if a:
#do something
print "Game over"
os.exit
#elif b:
#do something
print "Game over"
os.exit
break
while y:
#(...same form as the previous one^)
#get user input for the next turn
#while 1
#...
#while n
When I play the game, and the game over message is printed on to the screen, it still asks for the user input despite being told to stop.
This is how sys.exit() should work. Sys.exit() should work if you import it and reach it. Maybe more troubleshooting information would be helpful? This works for python and python3
#!/usr/bin/env python
import sys
while 1==1:
print("This will print")
if 2==2:
print("This will also print")
sys.exit()
print("This will not print")
print("This will not print")
This is my terminal output:
Matts-MacBook-Pro:Desktop mw$ ./stupid.py
This will print
This will also print
edit.
As #goosfraba said, sys.exit(0) would probably be best practice. The link provided says no argument can have undefined behavior. Another argument like 1 or "This is an error message" would also work.
With these small alterations, I managed to make this work:
import os
while True:
#do something
#for loop
if False:
#do something
print "Game over A"
os._exit(0)
elif True:
#do something
print "Game over B"
os._exit(0)
break
print "Not over"
Output:
Game over B
Note the lack of the Not over output.
Perhaps _exit(<status>) is what you need?
You should use:
sys.exit(n)
Where the optional n is an integer with the exit status.
Please check: https://docs.python.org/2/library/sys.html

Is there a workaround for "try: input() except KeyboardInterrupt:"

I've searched this topic to no avail for hours.
Is it possible to do something along the lines of:
try:
input_var = input('> ')
except KeyboardInterrupt:
print("This will not work.")
But when I try this and do CTRL-C, it just does nothing.
Is there any other way to achieve this?
Using Windows 10, Python 3.5.2, and Powershell
Note: I am not using the input_var for printing, I am doing 3 if/elif/else statements based around it.
It sounds like you would be interested in the signal module.
This Answer demonstrates how to use the signal module to capture Ctrl+C, or SIGINT.
For your use case, something along the lines of the following would work :
#!/usr/local/bin/python3
import signal
def signal_handler(signal, frame):
raise KeyboardInterrupt('SIGINT received')
signal.signal(signal.SIGINT, signal_handler)
try :
input_var = input('> ')
except KeyboardInterrupt :
print("CTRL+C Pressed!")

How to throw error and exit with a custom message in python

I've seen people suggesting sys.exit() in Python.
My question is that, is there any other way to exit the execution of current script, I mean termination, with an error.
Something like this:
sys.exit("You can not have three process at the same time.")
Currently my solution would be:
print("You can not have three process at the same time.")
sys.exit()
Calling sys.exit with a string will work. The docs mention this use explicitly:
In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.
There are 3 approaches, the first as lvc mentioned is using sys.exit
sys.exit('My error message')
The second way is using print, print can write almost anything including an error message
print >>sys.stderr, "fatal error" # Python 2.x
print("fatal error", file=sys.stderr) # Python 3.x
The third way is to rise an exception which I don't like because it can be try-catch
raise SystemExit('error in code want to exit')
it can be ignored like this
try:
raise SystemExit('error in code want to exit')
except:
print("program is still open")
You can also raise an error like this:
raise SystemExit('Error: 3 processes cannot run simultaneously.')
One advantage of this approach is that you don't have to import the Python sys module. This works on Linux with Python 3 and Python 2. I have not tested it on Windows or Mac OS.
You have to use import sys first
Then use sys.exit("your custom error message")

Terminating a Python Program

What command do you use in python to terminate a program?
i.e. the equivalent of "end" in basic, or "quit" in BASH.
I see that "break" takes you out of a loop, and "quit" is all tied up with "class" stuff that I do not comprehend yet.
i tried
import sys
sys.exit()
but it will display following error :
Traceback (most recent call last):
File "C:\Documents and Settings\....\Desktop\current file_hand\Python_1.py", line 131, in <module>
sys.exit()
SystemExit
is there any solution for it .
sys.exit(error_code)
Error_code will be 0 for a normal exit, 1 or some other positive number for an exit due to an error of some kind, e.g. the user has entered the wrong parameters.
sys.exit() "is undefined on some architectures", (although it worked when I tried it on my Linux box!)
The official python docs explains this more fully.
It's an extremely good idea for all your programs and scripts to follow the return code convention; 0 for OK, something else for error, (normally 1)
For example, if you run a script which grabs some data out of a database; returning 0 and no output, means the database is perfectly fine there's just nothing in it (or nothing matching your query). returning 1 and no output means there is a fault with the database, the whole process should abort, because to continue would corrupt the other system too.
sys.exit() raises the SystemExit exception.
If you don't catch that exception the program ends.
Since you're getting that output, I'm not sure what is happening, but I guess that you're catching all exceptions and printing them yourself:
try:
...
except:
print exception somehow
raise
If that's the case, don't do that. catch Exception instead:
...
except Exception:
...
That way you won't catch things not meant to be catched (like SystemExit).
You should also consider alternatives to exiting directly. Often return works just as well if you wrap code in a function. (Better, in fact, because it avoids sys.exit() weirdness.)
def main():
...do something...
if something:
return # <----- return takes the place of exit
...do something else...
main()
sys.exit() #to exit the program
return #to exit from a function
import sys
sys.exit(0)
Try running a python interpreter out of your IDE. In my Windows installation the simple command line python.exe, both options work:
>>> import sys
>>> sys.exit()
or
>>> raise SystemExit
In your case, your error is likely that you have a bare except block that is catching the SystemExit exception, like this:
import sys
try:
sys.exit(return_code)
except:
pass
The correct way to fix your problem is to remove the except: portion, and instead just catch the Exceptions you expect to be possibly raised. For example:
try:
# Code which could raise exceptions
except (NameError, ValueError):
# Do something in case of NameError or ValueError, but
# ignore other exceptions (like SystemExit)
However, if you really wanted your program to exit, the following code will work:
import os
try:
os._exit(return_code)
except:
pass
This will exit even with the except: clause, as it just directly calls the C function of the same name which kills your process. This is not recommended unless you know what you are doing, since this will not call cleanup handlers or flush open IO buffers.
I met this problem on Windows where I needed to close ParaView (I could not use pvbatch or pvpython, because of OpenGL initialization, and sys.exit does not work)
Below is the specific solution for Windows.
# import os module
import os
# delete given process
os.system('wmic process where name="Process_Name" delete')
# for example
os.system('wmic process where name="paraview.exe" delete')
Source of this solution is here

Categories