如何在Django环境中执行外部脚本 [英] How to execute external script in the Django environment
问题描述
我正在尝试在Django控制台使用的环境中执行外部代码段,以进行调试和类似终端的用途,以便它可以连接到db等。
I am trying to execute an external snippet for debugging and terminal-like purposes in the environment the Django console uses so it can connect to the db, etc.
基本上,我只是出于相同的原因使用它,因为我会在控制台上摆弄一些东西,但是我使用了更长的代码片段来输出一些格式化的信息,因此使用IDE在实际文件中处理该代码非常方便。
Basically, I am just using it for the same reason one would fiddle with the console but I am using longer snippets to output some formatted information so it is handy to have that code in an actual file manipulated with an IDE.
回答说,您可以通过执行 python manage.py shell< snippet.py
,但没有看到成功的结果。而且,尽管没有错误报告,但是我没有得到例外的输出,而是只有一系列>>>
提示。
An answer said you could do that by executing python manage.py shell < snippet.py
but I did not see a successfull result. And although no errors are reported, I am not getting the excepted output, but only a series of >>>
prompts.
那么我该怎么做?
顺便说一句,我正在使用PyCharm,以防该IDE可以简便地执行此操作或执行其他操作
By the way, I am using PyCharm, in case this IDE has a shorthand way of doing this or any special tool.
推荐答案
我会说创建一个新的自定义管理命令是实现此目标的最佳方法。
I would say creating a new Custom management command is the best way to achieve this goal.
但是您可以在Django环境中运行脚本。有时我会用它来运行一个脚本或一些简单的测试。
But you can run your script in a django environment. I use this sometimes to run a oneoff script or some simple tests.
您必须设置环境变量 DJANGO_SETTINGS_MODULE
到您的设置模块,然后您必须调用 django.setup()
You have to set the environment variable DJANGO_SETTINGS_MODULE
to your settings module and then you have to call django.setup()
我从 manage.py
脚本,您必须设置正确的设置模块!
I copied these lines from the manage.py
script, you have to set the correct settings module!
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.local")
django.setup()
这是我有时使用的简单模板脚本:
Here is a simple template script which I use sometimes:
# -*- coding: utf-8 -*-
import os
import django
# you have to set the correct path to you settings module
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.local")
django.setup()
from project.apps.bla.models import MyModel
def run():
# do the work
m = MyModel.objects.get(pk=1)
if __name__ == '__main__':
run()
重要的是要注意项目导入必须放在之后并调用 django.setup()
。
It is important to note that all project imports must be placed after calling django.setup()
.
这篇关于如何在Django环境中执行外部脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!