我需要从Django shell中执行一个Python脚本。我试着:
./manage.py shell << my_script.py
但这并没有起作用。它只是在等我写点什么。
我需要从Django shell中执行一个Python脚本。我试着:
./manage.py shell << my_script.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']在哪里
其他回答
@AtulVarma在不工作的接受答案下提供了一个非常有用的评论:
echo 'import myscript' | python manage.py shell
我刚刚发现一个有趣的东西是Django Scripts,它允许你用python manage.py runscript foobar来编写脚本。关于实现和结构的更多详细信息可以在这里找到,http://django-extensions.readthedocs.org/en/latest/index.html
如果IPython可用(pip install IPython),那么./manage.py shell将自动使用它的shell,然后你可以使用神奇的命令%run:
%run my_script.py
其实很简单,只要你打开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