我需要从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-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上测试。
我迟到了,但我希望我的回答能帮助到别人: 你可以在你的Python脚本中这样做:
import sys, os
sys.path.append('/path/to/your/django/app')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.conf import settings
你的其他东西在这里....
其实很简单,只要你打开django shell Python manage.py shell然后简单的写import test来导入test.py
# test.py
def x():
print('hello');
现在您可以执行该文件中的命令
test.x() // will print hello
首先检查你的文件。
py manage.py
如果显示您的文件
[contracts]
category_load
现在您可以通过输入powershell(terminal)来运行.py文件
py manage.py category_load
我带着与OP相同的问题来到这里,而我恰恰在问题中的错误中找到了我最喜欢的答案,这在Python 3中也适用:
./manage.py shell <<EOF
import my_script
my_script.main()
EOF