代码之家  ›  专栏  ›  技术社区  ›  Chris

python:argparse和列表列表

  •  2
  • Chris  · 技术社区  · 6 年前

    最小可验证示例:

    import argparse
    
    parser = argparse.ArgumentParser(description='...')
    parser.add_argument('-f','--file', type=str, nargs='+', help='file list')
    
    args = parser.parse_args()
    
    print(args.sparse[:])
    

    我把它叫做:

    python my_script.py -f f1 f2 f3 -f some_other_file1 some_other_file2 ...
    

    输出将是:

    [ [ f1 f2 f3 ] [ some_other_file1 some_other_file2 ] ]
    

    但是,在这种情况下,打印出来的只是:

     [ some_other_file1 some_other_file2 ]
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Michael H.    6 年前

    action='append' 可能是你想要的:

    import argparse
    
    parser = argparse.ArgumentParser(description='...')
    parser.add_argument('-f','--file', type=str, nargs='+', action='append', 
    help='file list')
    
    args = parser.parse_args()
    
    print(args.file)
    

    将给予

    $ python my_script.py -f 1 2 3 -f 4 5
    [['1', '2', '3'], ['4', '5']]
    
    推荐文章