在Django中执行Python脚本通常有两种方式:
management/commands
目录,然后在该目录下创建一个名为<command_name>.py
的Python文件,编写自定义的命令逻辑。最后在命令行中运行python manage.py <command_name>
即可执行该脚本。示例代码:
# myapp/management/commands/my_command.py
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'My custom command'
def handle(self, *args, **options):
# Your script logic here
print('Hello, Django!')
示例代码:
# script.py
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
import django
django.setup()
# Your script logic here
print('Hello, Django!')
然后在项目根目录下运行python script.py
即可执行该脚本。