我需要从Django shell中执行一个Python脚本。我试着:
./manage.py shell << my_script.py
但这并没有起作用。它只是在等我写点什么。
我需要从Django shell中执行一个Python脚本。我试着:
./manage.py shell << my_script.py
但这并没有起作用。它只是在等我写点什么。
当前回答
对于使用Django 1.7+的人来说,仅仅导入设置模块似乎是不够的。
经过一番挖掘,我找到了这个Stack Overflow的答案:https://stackoverflow.com/a/23241093
你现在需要:
import os, django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
django.setup()
# now your code can go here...
没有做上面的事情,我得到了一个django.core.exceptions.AppRegistryNoReady错误。
我的脚本文件是在相同的目录,我的django项目(即。和manage.py在同一个文件夹中)
其他回答
我迟到了,但我希望我的回答能帮助到别人:你可以在你的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']在哪里
如果你想在BG中更好地磨合:
nohup echo 'exec(open("my_script.py").read())' | python manage.py shell &
输出将在noup .out中
我刚刚发现一个有趣的东西是Django Scripts,它允许你用python manage.py runscript foobar来编写脚本。关于实现和结构的更多详细信息可以在这里找到,http://django-extensions.readthedocs.org/en/latest/index.html
其实很简单,只要你打开django shell Python manage.py shell然后简单的写import test来导入test.py
# test.py
def x():
print('hello');
现在您可以执行该文件中的命令
test.x() // will print hello
我带着与OP相同的问题来到这里,而我恰恰在问题中的错误中找到了我最喜欢的答案,这在Python 3中也适用:
./manage.py shell <<EOF
import my_script
my_script.main()
EOF