Ambika Saxena
Ambika Saxena

Reputation: 215

Properly terminate script without error message in Spyder

SO for my project in python, I am taking two inputs say a & b as integer values. Now the code goes like:

import sys
a = input("enter a")
b = input("enter b")
if a < b:
    print(" enter a greater than b and try again")
    sys.exit()

# Rest of the code is here

Now this works fine. But creates an extra statement

An exception has occurred, use %tb to see the full traceback.

SystemExit

And I do not want that as the user may think that the code's functioning is not proper. So is there any way that this statement is not shown or any other function which would exit the code without printing anything except the line which I have written?

NOTE I have tried exit() but it continues to execute the code beneath it. Also, I have noticed this related question but the approaches listed there don't work in this case.

EDIT: I am adding some more information. I need to put this exit function into a user-defined function so that every time the user enters some wrong data, the code will call this user-defined function and will exit the code. If I try to put my code in an if else statement like

def end():
    print("incorrect input try again")
    os.exit()

a = input("enter data")
if a < 10:
    end()
b = input ("enter data")
if b < 20:
   end()
# more code here

I don't know why but I can't even define this user-defined function in the end as it raises the error of undefined function end(). I'm using Python with Spyder on Windows.

Upvotes: 1

Views: 2896

Answers (2)

Snow
Snow

Reputation: 1138

You can use os._exit()

a = int(input("enter a"))
b = int(input("enter b"))
if a < b:
    print(" enter a greater than b and try again")
    os._exit(0)

Upvotes: 1

K. Kirsz
K. Kirsz

Reputation: 1420

This seems to work just fine:

import sys

def end():
    print("incorrect input try again")
    sys.exit(1)

a = input("enter data")
if int(a) < 10:
    end()
b = input ("enter data")
if int(b) < 20:
    end()

I used the sys.exit and fixed your conditions to avoid comparing string with integers. I cannot see any additional messages in the output. Only this:

>py -3 test2.py
enter data1
incorrect input try again
>

Please also take notice of this qoute from python docs:

The standard way to exit is sys.exit(n). [os]_exit() should normally only be used in the child process after a fork().

It also works in the repl

Upvotes: 1

Related Questions