我建议进行一些预处理来实现此目的:
Code:
def get_xyz_cmd_line(xyz_cmd_line):
# build a generator to iterate the cmd_line
cmd_line_gen = iter(xyz_cmd_line)
# we will separate the xyz's from everything else
xyz = []
remaining_cmd_line = []
# go through the command line and extract the xyz's
for opt in cmd_line_gen:
if opt.startswith('--xyz'):
# grab the opt and the arg for it
xyz.append((opt, cmd_line_gen.next()))
else:
remaining_cmd_line.append(opt)
# sort the xyz's and return all of them as -xyz # -xyz # ...
return list(it.chain(*[
('--xyz', x[1]) for x in sorted(xyz)])) + remaining_cmd_line
To Test:
import argparse
import itertools as it
parser = argparse.ArgumentParser(description='Get my Option')
parser.add_argument('--an_opt', metavar='N', type=int,
help='An option')
parser.add_argument('--xyz', metavar='N', type=int, action='append',
help='An option')
cmd_line = "--an_opt 1 --xyz1 10 --xyz3 31 --xyz2 25 ".split()
args = parser.parse_args(get_xyz_cmd_line(cmd_line))
print(args)
Output:
Namespace(an_opt=1, xyz=[10, 25, 31])
To use:
名义上而不是固定的cmd_line
如上面的示例所示,这将通过以下方式调用:
args = parser.parse_args(get_xyz_cmd_line(sys.argv[1:]))
更新:如果您需要 --xyz=31 (即=
分隔器):
那么你需要改变:
# grab the opt and the arg for it
xyz.append((opt, cmd_line_gen.next()))
To:
if '=' in opt:
xyz.append(tuple(opt.split('=', 1)))
else:
# grab the opt and the arg for it
xyz.append((opt, cmd_line_gen.next()))