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

时间:2012-04-08 17:17:23

标签: 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)

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

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

3 个答案:

答案 0 :(得分: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()
    
  2. 启动shell plus(启动嵌入式IPython shell)。

    python manage.py shell_plus

  3. 手动运行启动脚本。

    In [1]: %run shell_plus_startup.py
    
  4. 然后您可以使用已定义的变量,您导入的模块等。

    In [2]: tod
    Out[2]: datetime.date(2012, 7, 14)
    
  5. 另请参阅此答案:scripting ipython through django's shell_plus

答案 1 :(得分:0)

如果您使用的是django-extensions-shell_plus,我找到了一种方法。它有点hacky,但通过这种方式,您的启动文件将完全自动加载,您不必在ipython会话开始时键入任何run-command。

因此我编辑了django_extensions dir中的文件shells.py,我的案例位于/usr/local/lib/python2.7/dist-packages/django_extensions/management/shells.py。我在函数import_objects(options, style):中添加了这些行,因此它导入了由环境参数startup.py定义的文件PYTHONSTARTUP的内容。

def import_objects(options, style):
    # (...)
    import os, sys, pkgutil
    if 'PYTHONSTARTUP' in os.environ:
        try:
            sys.path.append(os.environ['PYTHONSTARTUP'])
            import startup
            content = [element for element in dir(startup) if not element.startswith('__')]
            for element in content:
                imported_objects[element] = getattr(startup, element)
        except Exception, ex:
            sys.exit("Could not import startup module content, Error:\n%s" % ex)

现在,当我启动shell_plus-shell时,我将环境变量提供给我的启动python脚本。使用所有内容启动shell的我的bash脚本如下所示:

#!/bin/bash
export PYTHONSTARTUP=/home/ifischer/src/myproject/startup.py # tells shell_plus to load this file
python /home/ifischer/src/myproject/manage.py shell_plus --ipython

现在我可以访问ipython会话开始时在startup.py中定义的所有方法和变量。

因此,您可以重用它并为每个项目提供自定义启动文件,预加载不同的方面。

也许有一种更简洁的方法可以包含我添加到shells.py中的行?但是这种方法现在适用于我。

答案 2 :(得分:0)

它会自动从django-extensions==1.5.6开始加载您的ipython配置。您还可以通过IPYTHON_ARGUMENTS将其他参数传递给ipython。文档: http://django-extensions.readthedocs.org/en/latest/shell_plus.html#configuration

相关问题