在嵌入式IPython实例中运行配置文件启动文件

hek*_*ran 7 python django ipython

我想使用带有user_ns字典的嵌入式IPython shell和我的配置文件配置(ipython_config.py和启动文件).目的是使用在启动时导入的模型运行Django shell.django-extensions实现了一个名为shell_plus的命令,它执行此操作:

https://github.com/django-extensions/django-extensions/blob/master/django_extensions/management/commands/shell_plus.py

from IPython import embed
embed(user_ns=imported_objects)
Run Code Online (Sandbox Code Playgroud)

问题是这不会加载我的启动文件.embed()调用load_default_config(),我想加载ipython_config.py.

如何使嵌入式IPython实例运行我的配置文件启动文件?

Sco*_*ter 1

我使用以下解决方法来运行我自己的 IPython 启动脚本,但仍然利用 shell_plus:

  1. shell_plus_startup.py在与 相同的目录中创建一个名为 的文件manage.py。例如:

    # File: shell_plus_startup.py
    # Extra python code to run after shell_plus starts an embedded IPython shell.
    # Run this file from IPython using '%run shell_plus_startup.py'
    
    # Common imports
    from datetime import date
    
    # Common variables
    tod = date.today()
    
    Run Code Online (Sandbox Code Playgroud)
  2. 启动 shell plus(启动嵌入式 IPython shell)。

    python manage.py shell_plus

  3. 手动运行启动脚本。

    In [1]: %run shell_plus_startup.py
    
    Run Code Online (Sandbox Code Playgroud)
  4. 然后您可以使用您定义的变量、导入的模块等。

    In [2]: tod
    Out[2]: datetime.date(2012, 7, 14)
    
    Run Code Online (Sandbox Code Playgroud)

另请参阅这个答案:scripting ipython through django's shell_plus