Reputation: 1637
My python script has a couple of sys.exit() calls to terminate under certain conditions. To test it, I open up a python shell and run exec(open('script.py').read())
. Whenever I hit a sys.exit()
call, the script terminates, along with the python shell, which is irritating.
So I try to get creative and attempt to determine whether my script is run from the commandline or from the shell by examining the stack. Source : Detect if python script is run from an ipython shell, or run from the command line
def exit_now(exit_status):
os.system('pause')
if PythonShell: # how do I return to the python shell ?
???
else: # exit if we are running from the commandline
sys.exit(exit_status)
...
# check if this was run from inside a python shell
frames = len(inspect.stack())
if frames > 1:
PythonShell = True
else:
PythonShell = False
...
if condition1:
exit_now(1)
if condition2:
exit_now(2)
...
exit_now(0)
How do I drop back to the python shell after terminating a script ?
Upvotes: 2
Views: 1957
Reputation: 97651
How about:
try:
exec(open('script.py').read())
except SystemExit:
pass
Upvotes: 2