Python:带有列表列表的 Argparse

don*_*lan 8 python argparse

最小可验证示例:

import argparse

parser = argparse.ArgumentParser(description='...')
parser.add_argument('-f','--file', type=str, nargs='+', help='file list')

args = parser.parse_args()

print(args.sparse[:])
Run Code Online (Sandbox Code Playgroud)

这个想法是我称之为:

python my_script.py -f f1 f2 f3 -f some_other_file1 some_other_file2 ...
Run Code Online (Sandbox Code Playgroud)

输出将是:

[ [ f1 f2 f3 ] [ some_other_file1 some_other_file2 ] ]
Run Code Online (Sandbox Code Playgroud)

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

 [ some_other_file1 some_other_file2 ]
Run Code Online (Sandbox Code Playgroud)

Mic*_* H. 12

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)
Run Code Online (Sandbox Code Playgroud)

会给

$ python my_script.py -f 1 2 3 -f 4 5
[['1', '2', '3'], ['4', '5']]
Run Code Online (Sandbox Code Playgroud)