skip to Main Content

IPython console is an extremely power instrument for the development. It used for research in general, application and algorithms developing both as sense catching.

Does there is a way to connect current context of Python app with IPython console? Like import ipyconsole; ipyconsole.set_interactive_from_here().

Here is much more complete situation.

First flow.
Below is some sort of running python app with inited DB and web-app route.

class App:
    def __init__(self):
        self.db = DB.new_connection("localhost:27018")
        self.var_A = "Just an example variable"
        
    def run(self):
        self.console = IPythonAppConsole(self) #Console Creation
        self.console.initialize()
        self.kernel = console.start()
        # print(self.kernel.connection_file)
        # << "kernel-12345.json"

    # let the app be some kind of web/flask application 
    @app.route('/items/<item_id>')
    def get_item(self, item_id=0):
        ### GOOD PLACE for
        ### <import ipyconsole; ipyconsole.set_interactive_from_here(self.kernel)> CODE
        item = self.db.find_one({'_id': item_id})
        print(item)
          

Second interactive flow. This is a valuable target.

$: ipython console --existing "kernel-12345.json"
<< print(self.db.uri)
>> "localhost:27018"
<< print(item_id)
>> 1234567890

Does there is a common sense way to implement these two flows? Maybe there is some sort of magic combination of pdb and ipython kernel?


By the way there are another interactive ways to communicate with applications:

  1. Debugging. Debug app with pdb/ipdb/web-pdb, using such snipper import pdb; pdb.set_trace() in any line in code.
  2. Generate IPython notebook snippet from python code. Anywhere pyvt.

Today I looking for the answer inside IPython/shellapp, kernelapp sources with Jupyter console and dynamic variable sharing through Redis. Thanks for any kind of ideas!

enter image description here

2

Answers


  1. One possible way for you to achieve this is to use ipdb and iPython combo.

    x = 2
    
    ipdb.set_trace()
    
    x = 4
    

    When you run the code, it drops into a ipdb shell

    ❯ python3 test.py
    > /Users/tarunlalwani/Documents/Projects/SO/opa/test.py(7)<module>()
          5 ipdb.set_trace()
          6
    ----> 7 x = 4
    ipdb>
    

    And then you can drop into a ipython shell from there

    ipdb> from IPython import embed
    ipdb> embed()
    Python 3.9.1 (default, Jan  8 2021, 17:17:43)
    Type 'copyright', 'credits' or 'license' for more information
    IPython 7.19.0 -- An enhanced Interactive Python. Type '?' for help.
    
    In [1]: x
    Out[1]: 2
    
    In [2]:
    
    Login or Signup to reply.
  2. Maybe Flask shell is what you are looking for https://flask.palletsprojects.com/en/1.1.x/shell/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search