17

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?

static_rtti
  • 53,760
  • 47
  • 136
  • 192
  • 3
    Thanks to all! For the record, the easiest way to use the code module to achieve this is the following: import code code.interact(local=globals()) – static_rtti Apr 12 '10 at 12:15
  • 3
    To get local variables into the namespace as well, you need `code.interact(local=dict(globals(), **locals())`. Note the addition of `**locals`. I was wondering this question myself, and your comment was the best answer I found :-) – Cody Piersall Jul 03 '13 at 21:34

6 Answers6

12

Use the -i flag when you start Python and set an atexit handler to run when cleaning up.

File script.py:

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

and then you just start Python with the -i flag:

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

Goodbye
Duncan
  • 92,073
  • 11
  • 122
  • 156
9

The code module will allow you to start a Python REPL.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
8

With IPython v1.0, you can simply use

from IPython import embed
embed()

with more options shown in the docs.

beardc
  • 20,283
  • 17
  • 76
  • 94
7

To elaborate on IVA's answer: embedding-a-shell, incoporating code and 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()
Gregg Lind
  • 20,690
  • 15
  • 67
  • 81
5

Not exactly the thing you want but python -i will start interactive prompt after executing the script.

-i : inspect interactively after running script, (also PYTHONINSPECT=x) and force prompts, even if stdin does not appear to be a terminal

$ python -i your-script.py
Python 2.5.4 (r254:67916, Jan 20 2010, 21:44:03) 
...
>>> 
Łukasz
  • 35,061
  • 4
  • 33
  • 33
-1

You may call python itself:

import subprocess

print "Hola"

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

print "Adios"
OscarRyz
  • 196,001
  • 113
  • 385
  • 569