我的 python 脚本有几个 sys.exit() 调用可以在特定条件下终止。为了测试它,我打开了一个 python shell 并运行 exec(open('script.py').read())
。每当我调用 sys.exit()
时,脚本就会终止,同时 python shell 也会终止,这很烦人。
因此,我尝试发挥创意,并尝试通过检查堆栈来确定我的脚本是从命令行运行还是从 shell 运行。来源: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)
如何在终止脚本后返回到 python shell?
最佳答案
python -i <script>
'i' 用于交互。
关于python - 退出脚本后如何返回到 python shell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29693846/