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

时间:2015-04-17 08:16:08

标签: 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?

2 个答案:

答案 0 :(得分:4)

python -i <script>

'我'用于互动。

答案 1 :(得分:2)

怎么样:

try:
    exec(open('script.py').read())
except SystemExit:
    pass