python - 退出脚本后如何返回到 python shell?

标签 python shell python-3.x

我的 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/

相关文章:

linux - 如何用时间戳显示历史

bash - Unix 删除所有出现的字符并保存

python - PyQt5 动画行为作为类属性

python - 是否可以在 x 轴(经度)上移动 geopandas 世界地图?

python - 如何删除span标签内的span标签

python - 使用没有 "with" block 的上下文管理器

python - 如何使用 numpy 数组有效地获取由特定值选择的索引列表?

python - 带条件的随机数生成器 - Python

java - 如何更改默认编译器?

python - 逐行打印嵌套列表 - Python