如何自定义Django manage.py shell?

时间:2021-01-07 23:19:12

Almost every time I use the manage.py shell in Django, I want to have certain things imported. I want to import * from my models.py module, for instance. Currently, my work around is to put all the imports in a file named s.py, and then after I fire up the shell I type execfile('s.py').

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

How can I customize manage.py so that it will do the imports automatically when I start the shell? I am using Django 1.4. Thank you.

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

Edit: I am adding more details to make my question more clear.

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

Here is what I originally did:

这是我最初做的:

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.

Typing 4 lines of boilerplate every time I start the shell is annoying. So I put those 4 lines in a file s.py. Now I do this:

每次启动shell时键入4行样板文件都很烦人。所以我将这4行放在文件s.py中。现在我这样做:

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

I want to get rid of the execfile('s.py') too. I want to make manage.py do those imports automatically when I start the shell.

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

4 个解决方案

#1


0  

I think you should not override the default shell or manage.py commands because you are going lo use them at other places . If you have a local settings file you might want to add them to your local settings file, But you could end up with circular imports if you are not careful . Also you should write your own extension to shell

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

Check this:

检查一下:

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

#2


0  

The shell sub-command simply invokes an interactive Python interpreter, so pointing the PYTHONSTARTUP UNIX environment variable to a file containing your desired imports would work. Here is the sequence:

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

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

Where pythonStartup.py is arbitrarily named and you can name it anything you like, including s.py (although that is probably not the best name for it). =:)

其中pythonStartup.py是任意命名的,您可以将它命名为任何您喜欢的名称,包括s.py(尽管这可能不是它的最佳名称)。 = :)

You can also create the following convenience alias for that in your personal .bash_profile:

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

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

and then simply use that:

然后简单地使用:

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

Now, you need only to edit the pythonStartup.py file to incorporate any changes to import behavior you might desire, and simply run the alias (... no need to edit or re-source your .bash_profile).

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

Here is what happens when I run python3 ./manage.py shell with the PYTHONSTARTUP environment variable properly pointed to the file I want imports to come from:

以下是当我运行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]:

EDIT:

编辑:

An additional tip that I forgot to mention.

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

If you place pythonStartup.py in the root directory of your Django projects, then creating the alias as follows:

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

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

allows you to cd to the root directory of whatever Django project you're currently working on, and the alias will invoke that particular project's pythonStartup.py. This approach adds flexibility.

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

#3


0  

Check django-extensions, it provides a shell_plus management command that automatically imports all models for installed applications:

检查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)

Note that custom app models are also imported.

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

#4


0  

There is a django extension for you, its shell_plus.

你有一个django扩展,它的shell_plus。

1. pip install django-extensions

1. pip install django-extensions

2. add 'django-extensions' to your settings.py's INSTALLED_APPS[]

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

3. RUN COMMAND >>>>> python manage.py shell_plus

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

#1


0  

I think you should not override the default shell or manage.py commands because you are going lo use them at other places . If you have a local settings file you might want to add them to your local settings file, But you could end up with circular imports if you are not careful . Also you should write your own extension to shell

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

Check this:

检查一下:

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

#2


0  

The shell sub-command simply invokes an interactive Python interpreter, so pointing the PYTHONSTARTUP UNIX environment variable to a file containing your desired imports would work. Here is the sequence:

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

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

Where pythonStartup.py is arbitrarily named and you can name it anything you like, including s.py (although that is probably not the best name for it). =:)

其中pythonStartup.py是任意命名的,您可以将它命名为任何您喜欢的名称,包括s.py(尽管这可能不是它的最佳名称)。 = :)

You can also create the following convenience alias for that in your personal .bash_profile:

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

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

and then simply use that:

然后简单地使用:

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

Now, you need only to edit the pythonStartup.py file to incorporate any changes to import behavior you might desire, and simply run the alias (... no need to edit or re-source your .bash_profile).

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

Here is what happens when I run python3 ./manage.py shell with the PYTHONSTARTUP environment variable properly pointed to the file I want imports to come from:

以下是当我运行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]:

EDIT:

编辑:

An additional tip that I forgot to mention.

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

If you place pythonStartup.py in the root directory of your Django projects, then creating the alias as follows:

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

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

allows you to cd to the root directory of whatever Django project you're currently working on, and the alias will invoke that particular project's pythonStartup.py. This approach adds flexibility.

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

#3


0  

Check django-extensions, it provides a shell_plus management command that automatically imports all models for installed applications:

检查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)

Note that custom app models are also imported.

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

#4


0  

There is a django extension for you, its shell_plus.

你有一个django扩展,它的shell_plus。

1. pip install django-extensions

1. pip install django-extensions

2. add 'django-extensions' to your settings.py's INSTALLED_APPS[]

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

3. RUN COMMAND >>>>> python manage.py shell_plus

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