Created
October 1, 2020 03:08
-
-
Save knktc/9e2c8aa19ae4f9e3d4408e9b0edf664d to your computer and use it in GitHub Desktop.
A Django custom command, to run script in current project environment.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
@author:knktc | |
@contact:me@knktc.com | |
""" | |
import os | |
import sys | |
import argparse | |
from django.core.management.base import BaseCommand | |
class Command(BaseCommand): | |
help = 'Run script in current project environment' | |
def add_arguments(self, parser): | |
parser.add_argument('script', type=str, nargs=argparse.REMAINDER, | |
help='script file path and args') | |
def handle(self, *args, **options): | |
# get args | |
args = options['script'] | |
script_path = args[0] | |
# check file existence | |
if not os.path.isfile(script_path): | |
self.stderr.write(f'No such file: [{script_path}]') | |
sys.exit(1) | |
# set args | |
sys_argv = [script_path] + args[1:] | |
sys.argv = sys_argv | |
# run | |
with open(script_path, 'r') as f: | |
exec(f.read(), {'__name__': '__main__'}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment