Harry Callahan
Harry Callahan

Reputation: 31

Is it possible to launch the Python interpreter at runtime?

I would like to know if a Python script could launch the Python interpreter at runtime, making variables accessible from the interpreter.

Let me explain myself. Let's say I have the following script:

x = 20
LaunchInterpreter() #Imaginary way to launch the Interpreter

Now, the interpreter is launched and we can play around with variables.

>>> x               #x defined value by the script
20
>>> x*x
400

Upvotes: 2

Views: 815

Answers (2)

bgporter
bgporter

Reputation: 36494

The -i command line option to Python forces the launching of a command interpreter after a script completes:

python --help
usage: /Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
< ... >
-i     : inspect interactively after running script; forces a prompt even
         if stdin does not appear to be a terminal; also PYTHONINSPECT=x

so given a file test.py that contains:

x = 7
y = "a banana"

you can launch python with the -i option to do exactly what you'd like to do.

python -i test.py
>>> x
7
>>> y
'a banana'
>>>

Upvotes: 0

Ewan
Ewan

Reputation: 15058

If you're looking for a dynamic interpreter you can use pdb. It is just a debugger though so should be used only for that purpose but can be used like in the following way;

x = 20
import pdb
pdb.set_trace()

Now you will have an interpreter and you can play around with the variables.

I don't know if this is suitable in your situation but it's the closest thing I can think of with the information provided.

Edit 1:

As stated in the comments by skishore you can also use code.interact(local=locals()) so:

x = 20
import code
code.interact(local=locals())

Upvotes: 3

Related Questions