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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 01:03:25  来源:igfitidea点击:

Is there a way to make python become interactive in the middle of a script?

pythonscriptinginteractive

提问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

With IPython v1.0, you can simply use

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

from IPython import embed
embed()

with more options shown in the docs.

文档中显示了更多选项。

回答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

The codemodule will allow you to start a Python REPL.

code模块将允许您启动 Python REPL。

回答by Gregg Lind

To elaborate on IVA's answer: embedding-a-shell, incoporating codeand Ipython.

详细说明 IVA 的答案: embedding-a-shellcodeincoporating 和 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 -iwill 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"