在Django之外运行Python脚本 [英] Running a Python script outside of Django
问题描述
我有一个脚本,使用Django ORM功能,以及其他外部库,我想在Django之外运行(即从命令行执行)。
I have a script which uses the Django ORM features, amongst other external libraries, that I want to run outside of Django (that is, executed from the command-line).
编辑:目前,我可以通过导航到URL来启动它。
At the moment, I can launch it by navigating to a URL...
如何设置这个环境?
推荐答案
最简单的方法是将脚本设置为 manage.py
子命令。这很容易做:
The easiest way to do this is to set up your script as a manage.py
subcommand. It's quite easy to do:
from django.core.management.base import NoArgsCommand, make_option
class Command(NoArgsCommand):
help = "Whatever you want to print here"
option_list = NoArgsCommand.option_list + (
make_option('--verbose', action='store_true'),
)
def handle_noargs(self, **options):
... call your script here ...
将它放在一个文件中,在你的任何应用程序的管理/命令/ yourcommand.py(空的 __ init __。py
每个文件),现在您可以使用 ./ manage.py yourcommand
来调用脚本。
Put this in a file, in any of your apps under management/commands/yourcommand.py (with empty __init__.py
files in each) and now you can call your script with ./manage.py yourcommand
.
这篇关于在Django之外运行Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!