我需要从Django shell中执行一个Python脚本。我试着:

./manage.py shell << my_script.py

但这并没有起作用。它只是在等我写点什么。


当前回答

如果你的脚本中没有很多命令,使用它:

manage.py shell --command="import django; print(django.__version__)"

Django文档在manage.py shell上

其他回答

注意,这个方法在django的最新版本中已经被弃用了!(> 1.3)

另一个答案是,您可以将它添加到my_script.py的顶部

from django.core.management import setup_environ
import settings
setup_environ(settings)

然后用python在settings。py目录下执行my_script.py,但这有点棘手。

$ python my_script.py

我刚刚发现一个有趣的东西是Django Scripts,它允许你用python manage.py runscript foobar来编写脚本。关于实现和结构的更多详细信息可以在这里找到,http://django-extensions.readthedocs.org/en/latest/index.html

首先检查你的文件。

py manage.py

如果显示您的文件

[contracts]
category_load

现在您可以通过输入powershell(terminal)来运行.py文件

py manage.py category_load

如果你正在使用虚拟环境,试试这个:-

Python manage.py shell

要使用这些命令,您必须在虚拟环境中。本用途:-

被vir_env_name

例如:-

dc@dc-comp-4:~/mysite$ workon jango
(jango)dc@dc-comp-4:~/mysite$ python manage.py shell
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> 

注意:这里mysite是我的网站名称,jango是我的虚拟环境名称

其实很简单,只要你打开django shell Python manage.py shell然后简单的写import test来导入test.py

# test.py
def x():
  print('hello');

现在您可以执行该文件中的命令

test.x() //  will print hello