1

I have a small python script which I have written specifically for this question.

#!/usr/bin/python3

import sys

def testfunc(test):
  if test == 1:
    print("test is 1")
  else:
    print("test is not 1")
    sys.exit(0)

try:
  testfunc(2)
except:
  print("something went wrong")

print("if test is not 1 it should not print this")

What I was expecting is that when test = 2 the script should exit. Instead what I get is this;

test is not 1
something went wrong
if test is not 1 it should not print this

I am new to python but not to scripting/coding. I have searched all over the place and every answer is simply "use sys.exit()"

Well it seems that sys.exit() has what seems to be unexpected behaviour when it is contained within try/except. If I remove the try it behaves as expected

Is this normal behaviour? If so is there a way to hard exit the script with out it continuing to execute into the exception block when test = 2?

Note: this is sample code that is a simplified version of the logic I am intending to use in another script. The reason the try/except is there is because testfunc() will be called using a variable and I want to catch the exception if an invalid function name is provided

Thanks in advance

Edit: I have also tried quit(), exit(), os._exit() and raise SystemExit

brettg
  • 23
  • 3

1 Answers1

0

Here, sys.exit(0) raises a SystemExit exception.

Since you put the calling code inside a Try-Except block, it's as expected caught. If you want to propagate the exception, recall a sys.exit() with the code status:

try:
  testfunc(2)

except SystemExit as exc:
  sys.exit(exc.code) # reperform an exit with the status code
except:
  print("something went wrong")

print("if test is not 1 it should not print this")
Amessihel
  • 5,891
  • 3
  • 16
  • 40
  • Thanks Amessihel, I tried your code and it worked, I will incorporate that into my script proper. I am assuming that there is no option for a hard exit such as php die() or bash exit in python then? – brettg Feb 11 '19 at 23:24
  • @brettg, I don't think so, according of what I saw. But I'm not familiar with Python. – Amessihel Feb 12 '19 at 00:36