I want to exit Python if I encounter an exception in my function if that function is being executed from the command line, but want to raise an exception and print a stack trace if the my function is not run from the command line.
Right now I have
try:
#...
except Exception as e:
print('ERROR: Some useful message')
if __name__ == '__main__':
raise SystemExit
else:
raise e
but I feel like I'm either doing too much here, or too little.
Is there an idiomatic way to get a stack trace with the original exception when my function is run from the command line; but simply exit if it is being run from the command line?
Is there an idiomatic way to get a stack trace with the original exception when my function is run from the command line; but simply exit if it is being run from the command line?. I'm not sure if that makes. thanks.tryis just a test for something. When used from the command line in the context of a isolated command, it could fail without downstream consequences. But if the function has been imported and used, the user importing probably needs to decide for himself whether to exit, so I show the stack trace.