在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
即可執行該腳本。