【问题标题】:how to put in a list the values of multiple command line arguments如何将多个命令行参数的值放入列表中
【发布时间】:2014-11-27 16:24:39
【问题描述】:

我有一个 cli build.py 我称之为 build.py -t -c -f
当我解析命令行参数时,是否有内置方法来获取

列表
['t' = true,'c'=true,'f'=true,'s'=false]

以下是定义,不知道在dest 中要更改什么(添加[..] 不起作用。只是为了展示我试图实现的目标。

from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter

parser = ArgumentParser(description=program_license, formatter_class=RawDescriptionHelpFormatter)

parser.add_argument("-s","--stored_proc", dest="build_what['s']", action="store_true", help="build all stored procedures, or the folder/*.sql specified")
parser.add_argument("-t","--triggers", dest="build_what['t']", action="store_true", help="build all triggers, or the folder/*.sql specified")
parser.add_argument("-f","--functions", dest="build_what['f']", action="store_true", help="build all functions, or the folder/*.sql specified")
parser.add_argument("-c","--scripts", dest="build_what['c']", action="store_true", help="run all scripts, or the folder/*.sql specified")

【问题讨论】:

  • 你使用argparse吗?
  • 已修改我正在使用 ArgumentParser,从 argparse import ArgumentParser from argparse import RawDescriptionHelpFormatter
  • ['t' = true,'c'=true,'f'=true,'s'=false] 不是 Python 列表。你是说字典 ({'t':true,'c':true,'f':true,'s':false})?
  • 嗯...对于我认为的这个特定任务来说它是一个列表还是字典对我来说并不重要
  • 如果您想要在Namespace 中使用短名称,请使用dest='s'。如果没有 dest 值,它将使用 'stored_proc'

标签: python parsing python-3.x command-line argparse


【解决方案1】:

参数解析器的parse_args 方法返回一个namespace。您可以在那里直接访问您的值作为属性:

args = parser.parse_args()
args.stored_proc # or `args.s` if you set `dest` to `'s'`

如果您需要字典访问(无论出于何种原因),您可以使用vars 进行转换:

>>> parser.parse_args(['-s', '-f'])
Namespace(c=False, f=True, s=True, t=False)
>>> vars(_)
{'f': True, 'c': False, 't': False, 's': True}

请注意,该字典将包含 所有 已注册的参数,而不仅仅是这四个。因此,如果您需要一个包含这四个值的字典,最好明确地创建它:

{'f': args.f, 'c': args.c, 't': args.t, 's': args.s}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 2012-05-20
    • 2012-10-21
    • 2021-02-01
    • 2015-11-30
    • 2013-01-22
    • 1970-01-01
    相关资源
    最近更新 更多