Rakesh Gupta
Rakesh Gupta

Reputation: 169

sys.exit() GCP Cloud Function

Have written GCP Cloud Function in Python 3.7. While executing, sys.exit() I'm getting 'A server error occurred ...'. I need to exit out of the function and have written following code.

import sys 
if str(strEnabled) == 'True':
        printOperation = "Operation: Enabling of user" 
else:
        sys.exit() #Exit From the Program

Please suggest, what I'm missing here.

Upvotes: 5

Views: 2478

Answers (3)

Mark Turner
Mark Turner

Reputation: 211

FYI for anyone else stumbling on this question, I found that raising an exception is the easiest way to exit out of a python cloud function if you can't easily return normally (as from an inner nested function that fails):

raise Exception("Something went wrong - exiting")

This will log an error, exit gracefully and avoid the instance running until timeout.

Upvotes: 0

Karthikeyan KR
Karthikeyan KR

Reputation: 1174

If you are calling a function from another function and needs to directly exit from the inner function without return you can use abort.

abort will directly return the response and exit the program from the place you are calling it.

import sys 
from flask import abort

if str(strEnabled) == 'True':
    printOperation = "Operation: Enabling of user" 
else:
    # abort(200) #return 200
    abort(500, description="Exit") #return 500

Note: cloud functions use flask module internally, so you need not install it separately.

Upvotes: 0

wjandrea
wjandrea

Reputation: 33145

Use return instead of sys.exit

Copied from bigbounty's comment

Upvotes: 4

Related Questions