有没有办法让Python在脚本中间变得交互?

17 投票
6 回答
12572 浏览
提问于 2025-04-15 21:25

我想做一些类似这样的事情:

do lots of stuff to prepare a good environement
become_interactive
#wait for Ctrl-D
automatically clean up

用Python可以做到吗?如果不行,你有没有其他方法可以实现同样的效果?

6 个回答

9

code模块可以让你启动一个Python的交互式命令行环境,也就是REPL(Read-Eval-Print Loop)。在这个环境里,你可以输入Python代码,立即看到结果,非常适合用来测试和学习Python。

12

在启动Python的时候,使用-i这个选项,并设置一个在程序结束时会运行的清理处理程序。

文件 script.py:

import atexit
def cleanup():
    print "Goodbye"
atexit.register(cleanup)
print "Hello"

然后你只需要用-i选项来启动Python:

C:\temp>\python26\python -i script.py
Hello
>>> print "interactive"
interactive
>>> ^Z

Goodbye
8

在IPython v1.0版本中,你可以简单地使用

from IPython import embed
embed()

更多的选项可以在文档中查看。

撰写回答