有没有办法让Python在脚本中间变成交互式?
我想做一些类似的事情:有没有办法让Python在脚本中间变成交互式?,python,scripting,interactive,Python,Scripting,Interactive,我想做一些类似的事情: do lots of stuff to prepare a good environement become_interactive #wait for Ctrl-D automatically clean up python有可能吗?如果没有,您是否看到了做同样事情的另一种方法?您可以将python本身称为: import subprocess print "Hola" subprocess.call(["python"],shell=True) print "
do lots of stuff to prepare a good environement
become_interactive
#wait for Ctrl-D
automatically clean up
python有可能吗?如果没有,您是否看到了做同样事情的另一种方法?您可以将python本身称为:
import subprocess
print "Hola"
subprocess.call(["python"],shell=True)
print "Adios"
模块将允许您启动Python REPL。不完全是您想要的,但是Python
-i
将在执行脚本后启动交互式提示
-i
:在运行脚本(也是PYTHONINSPECT=x)和强制提示后进行交互检查,即使stdin看起来不是终端
启动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
详细说明IVA的答案:,包括公司
code
和Ipython
def prompt(vars=None, message="welcome to the shell" ):
#prompt_message = "Welcome! Useful: G is the graph, DB, C"
prompt_message = message
try:
from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed(argv=[''],banner=prompt_message,exit_msg="Goodbye")
return ipshell
except ImportError:
if vars is None: vars=globals()
import code
import rlcompleter
import readline
readline.parse_and_bind("tab: complete")
# calling this with globals ensures we can see the environment
print prompt_message
shell = code.InteractiveConsole(vars)
return shell.interact
p = prompt()
p()
使用IPython v1.0,您只需使用
from IPython import embed
embed()
在中显示了更多选项。感谢大家!请注意,使用代码模块实现这一点的最简单方法如下:导入代码code.interact(local=globals())要将局部变量也放入命名空间,您需要
code.interact(local=dict(globals(),**locals())
。注意添加了**本地人
。我自己也在想这个问题,你的评论是我找到的最好的答案:-)你可以在任何地方使用它,它保留了范围。我以前就知道这一点!非常感谢。
from IPython import embed
embed()