2017-07-13 54 views
0

为positionals无效参数我想实现导入功能与必需和可选参数,以这种方式运行此:“需要”在Python命令

python manage.py import --mode archive 

在需要--modearchive也。

我正在使用argparse库。

class Command(BaseCommand): 
    help = 'Import' 

    def add_arguments(self, parser): 
     parser.add_argument('--mode', 
      required=True, 
     ) 
     parser.add_argument('archive', 
      required=True, 
      default=False, 
      help='Make import archive events' 
     ) 

但我recived错误:

TypeError: 'required' is an invalid argument for positionals 
+2

'archive'已被**需要,因为它是一个位置参数。 –

回答

7

您创建了一个位置参数(在名字前面没有--选项)。位置参数是总是需要。您不能使用required=True这样的选项,只需删除required即可。也删除default;一个必要的参数不能有默认值(其将绝不会还是使用):

parser.add_argument('archive', 
    help='Make import archive events' 
) 

如果你意味着archive是一个命令行开关,使用--archive代替。

2

我认为--mode archive的解释是:“模式是档案”,换句话说archive--mode参数的,而不是一个单独的参数。如果是这样,它将不得不是--archive这不是你想要的。

只是省略了archive的定义。