我需要从Django shell中执行一个Python脚本。我试着:
./manage.py shell << my_script.py
但这并没有起作用。它只是在等我写点什么。
我需要从Django shell中执行一个Python脚本。我试着:
./manage.py shell << my_script.py
但这并没有起作用。它只是在等我写点什么。
当前回答
从django-extensions运行脚本
python manage.py runscript scripty.py
一个示例script.py来测试它:
from django.contrib.auth.models import User
print(User.objects.values())
提及地址:http://django-extensions.readthedocs.io/en/latest/command_extensions.html,记录地址:
python manage.py runscript --help
还有一个教程。
在Django 1.9.6和Django -extensions 1.6.7上测试。
其他回答
如果你想执行启动脚本(例如,导入一些django模型来与它们交互工作),并保持在django shell中:
PYTHONSTARTUP=my_script.py python manage.py shell
其实很简单,只要你打开django shell Python manage.py shell然后简单的写import test来导入test.py
# test.py
def x():
print('hello');
现在您可以执行该文件中的命令
test.x() // will print hello
如果你的脚本中没有很多命令,使用它:
manage.py shell --command="import django; print(django.__version__)"
Django文档在manage.py shell上
迟到了。但这可能对某些人有帮助。
你只需要安装好脚本和django扩展。
只需运行django_extensions中可用的shell_plus,并导入您所编写的脚本。
如果你的脚本是scpt.py,并且它在foll文件夹中,你可以像下面这样运行脚本。
python manage.py shell_plus
然后在shell中导入脚本,如下所示。
>>> from fol import scpt
我迟到了,但我希望我的回答能帮助到别人:你可以在你的Python脚本中这样做:
步骤1:导入
import mysite.asgi
step2:需要执行一个Python脚本,只需输入:
python test.py
test.py文件是这样的:
import mysite.asgi
from polls.models import GMD_TABLE
print ( [obj.gt_GMD_name for obj in GMD_TABLE.objects.all()] )
最后:结果将是:
['ISHWARDI', 'JHENAIDHA', 'HVDC CIRCLE']
GMD_TABLE的值['ISHWARDI', 'JHENAIDHA', 'HVDC CIRCLE']在哪里