Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Python interactive console in current namespace?

I would like to have my Python code start a Python interactive console (REPL) in the middle of running code using something like code.interact(). But the console that code.interact() starts doesn't see the variables in the current namespace. How do I do something like:

mystring="hello"

code.interact()

... and then in the interactive console that starts, I should be able to type mystring and get "hello". Is this possible? Do I need to set the "local" argument of code.interact() to something? What would this be set to? How should it be called?

like image 788
user553702 Avatar asked Aug 23 '11 18:08

user553702


People also ask

How do I get to the Python console?

The console appears as a tool window every time you choose the corresponding command on the Tools menu. You can assign a shortcut to open Python console: press Ctrl+Alt+S , navigate to Keymap, specify a shortcut for Main menu | Tools | Python or Debug Console.

How do you use interactive mode in Python?

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 can you start an interactive interpreter session?

On Windows, bring up the command prompt and type "py", or start an interactive Python session by selecting "Python (command line)", "IDLE", or similar program from the task bar / app menu. IDLE is a GUI which includes both an interactive mode and options to edit and run files.


3 Answers

Try:

code.interact(local=locals())
like image 164
morsik Avatar answered Oct 12 '22 04:10

morsik


For debug I usually use this

from pdb import set_trace; set_trace()

it may help

like image 35
Facundo Casco Avatar answered Oct 12 '22 04:10

Facundo Casco


Another way is to start the debugger, and then run interact:

import pdb
pdb.set_trace()

Then from the debugger:

(Pdb) help interact
interact

        Start an interactive interpreter whose global namespace
        contains all the (global and local) names found in the current scope.
(Pdb) interact
*interactive*
>>>
like image 41
user1338062 Avatar answered Oct 12 '22 05:10

user1338062