【问题标题】:Use same argument several times in python [duplicate]在python中多次使用相同的参数[重复]
【发布时间】:2021-10-21 12:18:52
【问题描述】:

我想向argumentParser 添加参数,以便我可以多次使用它(带有一些值)而不是作为序列。 假设我有一个可选参数“-l”,它采用 str 值,那么我希望能够运行这样的东西(使用 python):

python myProg.py -l hay -l how -l are -l you

我在 add_argument 方法中使用了 nargs,但它只能这样工作:

python myProg.py -l hey how are you

我想得到一些帮助,谢谢。

【问题讨论】:

  • 请出示一些代码。
  • 不能做这样的事情吗? python myProg.py -l hay,how,are,you then split input?

标签: python


【解决方案1】:

您应该使用action='append'。见https://docs.python.org/3/library/argparse.html#action

【讨论】:

    【解决方案2】:

    这应该做你想做的事。请注意,在此解决方案中,如果一个标志会导致索引错误(即py example.py -l),那么它将被忽略。

    import sys
    
    text_positions = [i+1 for i, flag in enumerate(sys.argv) if flag == "-l"]
    text = [sys.argv[text_position] for text_position in text_positions if text_position < len(sys.argv)]
    # in case you want the arguments joined together as a string
    text_as_string = " ".join(text)
    
    print(text)
    print(text_as_string)
    

    执行上面的代码会产生以下结果:

    $ py example.py -l hey -l how -l are -l you
    ['hey', 'how', 'are', 'you']
    hey how are you
    

    【讨论】:

      猜你喜欢
      • 2021-06-05
      • 2020-11-03
      • 2013-07-18
      • 1970-01-01
      • 1970-01-01
      • 2018-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多