Django在脚本中执行类(Django execute class in script)

编程入门 行业动态 更新时间:2024-10-23 20:23:14
Django在脚本中执行类(Django execute class in script)

我在Django应用程序中执行脚本时遇到问题。 此脚本必须用于crontab中的作业。 生病提供我的脚本示例:

规范:Python:3.5.x Django:1.10.5

my_script.py

class SayHello(object): def print_args(self, arg1, arg2): print (arg1, arg2) if __name__ == "__main__": foo = SayHello() foo.print_args(sys.argv[1], sys.argv[2])

但主要的问题是当我想在这个脚本中包含模型时我得到错误: ImportError:没有名为“app”的模块

文件夹结构:

say_hello(主文件夹)

- > init .py

- > my_script.py

如何运行脚本但不会从import语句中获取错误到此脚本中。 任何建议都会很棒。

I have problem with executing script in Django application. This script must serve for job in crontab. So ill provide example of my script:

Specification: Python:3.5.x Django:1.10.5

my_script.py

class SayHello(object): def print_args(self, arg1, arg2): print (arg1, arg2) if __name__ == "__main__": foo = SayHello() foo.print_args(sys.argv[1], sys.argv[2])

But the main problem is when i want to include models in this script i got error: ImportError: No module named "app"

Folder structure:

say_hello (main folder)

-> init.py

-> my_script.py

How to run script but don't get errors from import statement into this script. Any advice would be great.

最满意答案

您的脚本必须位于应用程序的文件夹管理/命令/中。

脚本示例:

# -*- coding: utf-8 -*- # example.py from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): print "Hello word!!"

要运行脚本:

./manage.py example

这里有文档https://docs.djangoproject.com/en/1.10/howto/custom-management-commands/

You script must be in the folder management/commands/ of the app.

Script example:

# -*- coding: utf-8 -*- # example.py from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): print "Hello word!!"

To run the script:

./manage.py example

Here you have the documentation https://docs.djangoproject.com/en/1.10/howto/custom-management-commands/

更多推荐

本文发布于:2023-04-29 02:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1334560.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:脚本   Django   execute   script   class

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!