有没有一种方法可以让python在脚本中间变得交互式?

2024-06-18 11:32:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做些类似的事情:

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

用python有可能吗?如果没有,你看到做同样事情的另一种方式了吗?


Tags: oftoforprepare事情dointeractivegood
3条回答

^{}模块将允许您启动Python REPL。

使用IPython v1.0,您可以简单地使用

from IPython import embed
embed()

更多选项显示在docs

在启动Python时使用-i标志,并将atexit处理程序设置为在清理时运行。

文件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

相关问题 更多 >