Есть ли способ сделать python интерактивным в середине script?

Я хотел бы сделать что-то вроде:

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

Возможно ли это с помощью python? Если нет, вы видите другой способ сделать то же самое?

Ответы

Ответ 1

С IPython v1.0 вы можете просто использовать

from IPython import embed
embed()

с большим количеством параметров, показанных в docs.

Ответ 2

Используйте флаг -i при запуске Python и установите обработчик atexit для запуска при очистке.

Файл script.py:

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

а затем вы просто запустите Python с флагом -i:

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

Goodbye

Ответ 3

Модуль code позволит вам запустить Python REPL.

Ответ 4

Чтобы уточнить ответ IVA: embedding-a-shell, внося в отчёты 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()

Ответ 5

Не то, что вы хотите, но python -i начнет интерактивное приглашение после выполнения script.

-i: проверить интерактивно после запуска script (также PYTHONINSPECT = x) и форсировать подсказки, даже если stdin не является терминалом

$ python -i your-script.py
Python 2.5.4 (r254:67916, Jan 20 2010, 21:44:03) 
...
>>> 

Ответ 6

Вы можете вызвать сам python:

import subprocess

print "Hola"

subprocess.call(["python"],shell=True)

print "Adios"