Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 911
static_rtti Avatar asked Apr 09 '10 15:04

static_rtti


People also ask

How do you make a Python script interactive?

The interactive Python mode lets you run your script instantly via the command line without using any code editor or IDE. To run a Python script interactively, open up your command line and type python. Then hit Enter. You can then go ahead and write any Python code within the interactive mode.

How do I run a Python script in interactive mode?

A widely used way to run Python code is through an interactive session. To start a Python interactive session, just open a command-line or terminal and then type in python , or python3 depending on your Python installation, and then hit Enter .

What is script mode and interactive mode in Python?

Script Mode, is used when the user is working with more than one single code or a block of code. Interactive mode is used when an user wants to run one single line or one block of code. If one needs to write a long piece of Python code or if the Python script spans multiple files, interactive mode is not recommended.

What is an interactive Python shell?

Introduction. The Python interactive console (also called the Python interpreter or Python shell) provides programmers with a quick way to execute commands and try out or test code without creating a file.


1 Answers

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
like image 132
Duncan Avatar answered Sep 17 '22 20:09

Duncan