Skip to content

Instantly share code, notes, and snippets.

@ladyrick
Last active November 29, 2022 04:15
Show Gist options
  • Save ladyrick/ae8a557636839be76392f998df44cd5b to your computer and use it in GitHub Desktop.
Save ladyrick/ae8a557636839be76392f998df44cd5b to your computer and use it in GitHub Desktop.
enable `django manage.py shell` run a script
def patch_django_shell():
import os
import runpy
import sys
from functools import wraps
from unittest.mock import patch
from django.core.management.commands.shell import Command
original_handle = Command.handle
original_add_arguments = Command.add_arguments
@wraps(original_add_arguments)
def add_arguments(self, parser):
original_add_arguments(self, parser)
parser.add_argument(
"argv",
nargs="*",
help='if "argv" list is given, shell will run the script with args like an interpreter',
)
@wraps(original_handle)
def handle(self, **options):
if options["argv"]:
argv = options["argv"]
file_path = os.path.abspath(argv[0])
original_sys_path = sys.path
with (
patch("sys.argv", argv),
patch("sys.path", [os.path.dirname(file_path)] + original_sys_path),
):
runpy.run_path(file_path, run_name="__main__")
return
return original_handle(self, **options)
Command.add_arguments = add_arguments
Command.handle = handle
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment