簡體   English   中英

Python:如何將命令行arg作為字符串而不是元組傳遞?

[英]Python: How to pass command-line arg as string instead of tuple?

在我的Django站點中,我正在編寫一個管理命令來為所有模型或指定模型在固定裝置中生成示例數據。

第一個(也是唯一一個)位置arg應該指定要處理的app.model,或“ all”指定所有模型。

我遇到的問題是arg是一個元組,當我打印它時,它會顯示單個字符作為元組的每個元素。

這是我的代碼(就顯示arg而言):

    def add_arguments(self, parser):
        parser.add_argument(
            'args', type=str, metavar='app.model', nargs='?', default='all',
            help='Model in the form: app.model (example: clients.client)')

    def handle(self, *args, **kwargs):
        self.model = args

        print('args-type:', type(args))
        print('model-type:', type(self.model))
        print('model:', self.model)

請注意,我已將type=str指定為add_argument選項。

當我嘗試以下命令行時:

docker-compose exec api python manage.py gen_fixtures

...我得到以下輸出:

args-type: <class 'tuple'>
model-type: <class 'tuple'>
model: ('a', 'l', 'l')

如果在命令行上指定“ all”,則相同。 如果我嘗試這個:

docker-compose exec api python manage.py gen_fixtures clients.client

...我得到以下輸出:

args-type: <class 'tuple'>
model-type: <class 'tuple'>
model: ('c', 'l', 'i', 'e', 'n', 't', 's', '.', 'c', 'l', 'i', 'e', 'n', 't')

我知道,如果我用單個值(例如my_var = ('one value',)初始化代碼中的元組my_var = ('one value',)而忘記添加結尾逗號,則將得到與上述相同的結果。 但是在這種情況下,元組是在解析器中創建的,這超出了我的控制范圍。 為什么type=str沒有作用?

我只想要一個arg作為字符串。 我怎樣才能做到這一點?

您在這里混淆了兩件事。 *args是將變量參數傳遞給函數的內置Python方法; 它永遠是一個元組。 它與您恰好也稱為args的命令行選項無關。 您需要從第二個參數中提供的字典中獲取該信息。

def handle(self, *args, **kwargs):
    self.model = kwargs['args']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM