【问题标题】:How to customize the Django manage.py shell?如何自定义 Django manage.py shell?
【发布时间】:2013-06-24 22:12:40
【问题描述】:

几乎每次我在 Django 中使用 manage.py shell 时,我都希望导入某些东西。例如,我想从我的 models.py 模块中导入 *。目前,我的解决方法是将所有导入文件放在一个名为 s.py 的文件中,然后在启动 shell 后键入 execfile('s.py')。

如何自定义 manage.py 以便在我启动 shell 时自动执行导入?我正在使用 Django 1.4。谢谢。

编辑:我正在添加更多细节以使我的问题更清楚。

这是我最初做的:

bash> python manage.py shell
>>> from mysite.app.models import *
>>> from mysite.app2.models import *
>>> import decimal
>>> D = decimal.Decimal
# Now I am ready to work in this shell.

每次启动 shell 时都输入 4 行样板代码很烦人。所以我把这 4 行放在一个文件 s.py 中。现在我这样做:

bash> python manage.py shell
>>> execfile('s.py')
# Now I am ready to work.

我也想摆脱execfile('s.py')。我想让 manage.py 在我启动 shell 时自动执行这些导入。

【问题讨论】:

  • 通常你不想从 xxxx 导入 *,因为这可能会导致其他模块出现问题
  • PepperoniPizza: import * 在这种情况下很好,因为我是在交互式 shell 中进行的。
  • @SerMetAla 您是否考虑过使用 PYTHONSTARTUP UNIX 环境变量(如下面的答案所示)?

标签: python django django-manage.py manage.py


【解决方案1】:

shell 子命令只是调用交互式 Python 解释器,因此将 PYTHONSTARTUP UNIX 环境变量指向包含所需导入的文件即可。顺序如下:

user@linux$ export PYTHONSTARTUP='/path/to/my/django/pythonStartup.py'; python ./manage.py shell

pythonStartup.py 是任意命名的,您可以随意命名,包括 s.py(尽管这可能不是最好的名称)。 =:)

您还可以在您的个人 .bash_profile 中为其创建以下便利别名:

alias django-shell="export PYTHONSTARTUP='/path/to/my/django/pythonStartup.py'; python ./manage.py shell"

然后简单地使用它:

user@linux$ . ${HOME}/.bash_profile  # Normally you don't need to do this step.
user@linux$ django-shell

现在,您只需要编辑 pythonStartup.py 文件以合并您可能希望的对导入行为的任何更改,并且只需运行别名(...无需编辑或重新源你的 .bash_profile)。

当我运行 python3 ./manage.py shell 时会发生以下情况:PYTHONSTARTUP 环境变量正确指向我想要导入的文件:

user@linux$ python3 ./manage.py shell
Python 3.5.1 |Anaconda custom (64-bit)| (default, Dec  7 2015, 11:16:01) 
Type "copyright", "credits" or "license" for more information.

IPython 4.2.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

Importing base set of modules often used ...

import sys, os, random, pprint, operator
import time, math
import numpy, numpy as np
import numpy.linalg
import scipy, scipy as spimport scipy.optimize
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.pylab as pylab
import pandas as pd
import sklearn.datasets
import sklearn.feature_extraction
import sklearn.linear_model
import sklearn.neighbors
import sklearn.cluster
import sklearn.preprocessing
import sklearn.decomposition
import gensim.models.word2vec

In [1]:

编辑:

另外一个我忘了提的提示。

如果您将 pythonStartup.py 放在 Django 项目的根目录中,则创建别名如下:

alias django-shell="export PYTHONSTARTUP='./pythonStartup.py'; python ./manage.py shell"

允许您cd 到您当前正在处理的任何 Django 项目的根目录,并且别名将调用该特定项目的 pythonStartup.py。这种方法增加了灵活性。

【讨论】:

  • 这个。将PYTHONSTARTUP 添加到我的.env 文件允许我在启动shell 时导入我需要的所有内容,而无需安装任何其他应用程序。我更喜欢这个解决方案而不是shell_plus
【解决方案2】:

勾选django-extensions,它提供了shell_plus管理命令,自动导入已安装应用的所有模型:

user@host:~/git/project (devel)$ ./manage.py shell_plus
# Shell Plus Model Imports
from django.contrib.admin.models import LogEntry
from django.contrib.auth.models import Group, Permission, User
from django.contrib.contenttypes.models import ContentType
from django.contrib.sessions.models import Session
from custom_app1.models import MyModel1
from custom_app2.models import MyModel2
from custom_app3.models import MyModel3
# Shell Plus Django Imports
from django.utils import timezone
from django.conf import settings
from django.core.cache import cache
from django.db.models import Avg, Count, F, Max, Min, Sum, Q, Prefetch, Case, When
from django.core.urlresolvers import reverse
from django.db import transaction
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)

请注意,自定义应用模型也会被导入。

【讨论】:

  • 这将导入模型,但不会导入设置变量。问题有第四行要求D = decimal.Decimal
【解决方案3】:

我认为你不应该覆盖默认的 shell 或 manage.py 命令,因为你会在其他地方使用它们。如果您有本地设置文件,您可能希望将它们添加到本地设置文件中,但如果您不小心,最终可能会出现循环导入。此外,您应该编写自己的 shell 扩展

检查一下:

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

【讨论】:

    【解决方案4】:

    有一个适合你的 django 扩展,它的 shell_plus

    1。 pip install django-extensions

    2。将 'django-extensions' 添加到您的 settings.py 的 INSTALLED_APPS[]

    3。运行命令 >>>>> python manage.py shell_plus

    【讨论】:

      【解决方案5】:

      创建一个新的 shell 命令来继承和隐藏原始命令并运行任意代码并不难。

      我敢肯定这一定是个坏主意……但这很容易!我用它!

      这是一个例子:

      from django.core.management.commands.shell import Command as ShellCommand
      
      
      class Command(ShellCommand):
          def ipython(self, options):
              print("REMINDER - THIS IS JOHN'S HACKED SHELL")
              from IPython import start_ipython
      
              script_to_run_on_startup = """
              from django.conf import settings
              from my_app.models import MyModel
      
      
              expected_variables = ['In','Out','get_ipython','exit','quit', 'expected_variables']
              available_variables = [k for k in locals().keys() if k[0] != '_' and k not in expected_variables]
      
              print(f'\\navailable_variables:\\n{available_variables}')
              """
      
              argv = ['-c', script_to_run_on_startup, '-i']
      
              start_ipython(argv)
      

      现在将其粘贴到名为 shell.py 的命令文件中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-10-05
        • 2014-05-21
        • 1970-01-01
        • 1970-01-01
        • 2016-10-23
        • 1970-01-01
        • 2012-05-20
        相关资源
        最近更新 更多