我需要从Django shell中执行一个Python脚本。我试着:
./manage.py shell << my_script.py
但这并没有起作用。它只是在等我写点什么。
我需要从Django shell中执行一个Python脚本。我试着:
./manage.py shell << my_script.py
但这并没有起作用。它只是在等我写点什么。
当前回答
正如其他答案所指出但没有明确指出的那样,你实际上需要的不一定是从Django shell中执行脚本,而是在不使用Django shell的情况下访问应用程序。
这在Django版本和Django版本之间有很大不同。如果你在这篇文章中没有找到你的解决方案,答案在这里—— Django脚本访问模型对象,而不使用manage.py shell ——或者类似的搜索可能对你有帮助。
我必须以my_command.py开始
import os,sys
sys.path.append('/path/to/myproject')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.file")
import django
django.setup()
import project.app.models
#do things with my models, yay
然后运行python3 my_command.py
(Django 2.0.2)
其他回答
其实很简单,只要你打开django shell Python manage.py shell然后简单的写import test来导入test.py
# test.py
def x():
print('hello');
现在您可以执行该文件中的命令
test.x() // will print hello
如果你想执行启动脚本(例如,导入一些django模型来与它们交互工作),并保持在django shell中:
PYTHONSTARTUP=my_script.py python manage.py shell
我迟到了,但我希望我的回答能帮助到别人:你可以在你的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']在哪里
另一种方式是执行这个
echo 'execfile("/path_to/myscript.py")' | python manage.py shell --settings=config.base
它在Python2.7和Django1.9上运行
不建议你在shell中这样做——这是因为你不应该在django环境中执行随机脚本(但是有一些方法可以解决这个问题,参见其他答案)。
如果这是一个脚本,你将运行多次,这是一个好主意设置为一个自定义命令,即
$ ./manage.py my_command
要做到这一点,在你的应用程序的管理和命令的子目录中创建一个文件
my_app/
__init__.py
models.py
management/
__init__.py
commands/
__init__.py
my_command.py
tests.py
views.py
并在该文件中定义您的自定义命令(确保文件的名称是您想要从。/manage.py执行的命令的名称)
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, **options):
# now do the things that you want with your models here