Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue trying to pass file as an argument to a custom management command

Here is my code:

from django.core.management.base import BaseCommand, CommandError
import sys, os, shutil

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('--file', nargs='1', type=str)

    def handle(self, *args, **options):
        lists_file = options['file']

However, when I try to run the command with:

./manage.py: error: no such option: --file=test_lists.txt

I get an error:

Usage: ./manage.py create_test_lists [options] 

./manage.py: error: no such option: --file

I have verified that test_lists.txt exists in the same directory as manage.py. In addition the file for my command is located at my_app/management/commands/create_test_lists.py which seems right. Any ideas as to what I'm doing wrong?

like image 567
user3285713 Avatar asked Aug 23 '14 22:08

user3285713


1 Answers

  • No need for nargs if it's just one
  • Use argparse.FileType instread of str
  • See also https://docs.python.org/3/library/argparse.html#filetype-objects

Example:

import argparse

from django.core.management.base import BaseCommand


class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('--file', type=argparse.FileType('r'))

    def handle(self, *args, **options):
        lists_file = options['file']
like image 156
johntellsall Avatar answered Oct 16 '22 06:10

johntellsall