python 有没有办法让python在脚本中间变得交互?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2608751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to make python become interactive in the middle of a script?
提问by static_rtti
I'd like to do something like:
我想做类似的事情:
do lots of stuff to prepare a good environement
become_interactive
#wait for Ctrl-D
automatically clean up
Is it possible with python?If not, do you see another way of doing the same thing?
python可以吗?如果不行,你是否看到了另一种做同样事情的方式?
采纳答案by beardc
回答by Duncan
Use the -i flag when you start Python and set an atexit handler to run when cleaning up.
启动 Python 时使用 -i 标志并设置 atexit 处理程序在清理时运行。
File script.py:
文件脚本.py:
import atexit
def cleanup():
print "Goodbye"
atexit.register(cleanup)
print "Hello"
and then you just start Python with the -i flag:
然后您只需使用 -i 标志启动 Python:
C:\temp>\python26\python -i script.py
Hello
>>> print "interactive"
interactive
>>> ^Z
Goodbye
回答by Ignacio Vazquez-Abrams
回答by Gregg Lind
To elaborate on IVA's answer: embedding-a-shell, incoporating code
and Ipython.
详细说明 IVA 的答案: embedding-a-shell、code
incoporating 和 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()
回答by ?ukasz
Not exactly the thing you want but python -i
will start interactive prompt after executing the script.
不完全是你想要的东西,但 python-i
会在执行脚本后启动交互式提示。
-i
: inspect interactively after running script, (also PYTHONINSPECT=x) and force prompts, even if stdin does not appear to be a terminal
-i
: 在运行脚本后进行交互检查(还有 PYTHONINSPECT=x)并强制提示,即使 stdin 似乎不是终端
$ python -i your-script.py
Python 2.5.4 (r254:67916, Jan 20 2010, 21:44:03)
...
>>>
回答by OscarRyz
You may call python itself:
你可以调用 python 本身:
import subprocess
print "Hola"
subprocess.call(["python"],shell=True)
print "Adios"