问题描述
IPython 控制台是一个非常强大的开发工具。用于一般研究、应用和算法开发,均作为意义捕捉。
有没有办法将 Python 应用程序的当前上下文与 IPython 控制台连接起来?喜欢import ipyconsole; ipyconsole.set_interactive_from_here()
。
这里有更完整的情况。
第一个流程。 下面是某种正在运行的带有初始化数据库和网络应用程序路由的 python 应用程序。
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)
第二个交互流程。这是一个有价值的目标。
$: ipython console --existing "kernel-12345.json"
<< print(self.db.uri)
>> "localhost:27018"
<< print(item_id)
>> 1234567890
是否有实现这两个流程的常识方法?也许 pdb
和 ipython
内核有某种神奇的组合?
顺便说一下,还有另一种与应用程序通信的交互方式:
- 调试。使用 pdb/ipdb/web-pdb 调试应用程序,在代码的任何行中使用此类 snipper
import pdb; pdb.set_trace()
。 - 从 python 代码生成 IPython 笔记本代码段。任何地方pyvt。
今天我在 IPython/shellapp、kernelapp 源中寻找答案,Jupyter console 和动态变量共享通过 Redis。感谢您的任何想法!
解决方法
实现此目的的一种可能方法是使用 ipdb 和 iPython 组合。
x = 2
ipdb.set_trace()
x = 4
当你运行代码时,它会进入一个 ipdb shell
❯ python3 test.py
> /Users/tarunlalwani/Documents/Projects/SO/opa/test.py(7)<module>()
5 ipdb.set_trace()
6
----> 7 x = 4
ipdb>
然后你可以从那里进入一个 ipython
shell
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]:
,
也许 Flask shell 正是您要找的https://flask.palletsprojects.com/en/1.1.x/shell/