【发布时间】:2021-06-10 06:17:03
【问题描述】:
我正在努力列出 python 中带有可选和强制参数的命令的所有可能性。我需要它根据一些脚本的帮助输出在 bash 中生成一些自动完成脚本。
例如虚构的命令:
add disk -pool <name> { -diskid <diskid> | -diskid auto [-fx | -tdr] } [-fx] [-status { enable | disable } ]
其中:{} 必填,[] 可选,|或
上述命令的所有(24)种可能性的预期结果:
add disk -pool <name> -diskid <diskid>
add disk -pool <name> -diskid <diskid> -capacity_saving
add disk -pool <name> -diskid <diskid> -capacity_saving -status enable
add disk -pool <name> -diskid <diskid> -capacity_saving -status disable
add disk -pool <name> -diskid <diskid> -status enable
add disk -pool <name> -diskid <diskid> -status disable
add disk -pool <name> -diskid auto
add disk -pool <name> -diskid auto -capacity_saving
add disk -pool <name> -diskid auto -capacity_saving -status enable
add disk -pool <name> -diskid auto -capacity_saving -status disable
add disk -pool <name> -diskid auto -status enable
add disk -pool <name> -diskid auto -status disable
add disk -pool <name> -diskid auto -fx
add disk -pool <name> -diskid auto -fx -capacity_saving
add disk -pool <name> -diskid auto -fx -capacity_saving -status enable
add disk -pool <name> -diskid auto -fx -capacity_saving -status disable
add disk -pool <name> -diskid auto -fx -status enable
add disk -pool <name> -diskid auto -fx -status disable
add disk -pool <name> -diskid auto -tdr
add disk -pool <name> -diskid auto -tdr -capacity_saving
add disk -pool <name> -diskid auto -tdr -capacity_saving -status enable
add disk -pool <name> -diskid auto -tdr -capacity_saving -status disable
add disk -pool <name> -diskid auto -tdr -status enable
add disk -pool <name> -diskid auto -tdr -status disable
我试过import intertool + product(),但它只适用于不太复杂的命令,如{ -diskid <diskid> | -diskid auto },所以如果括号中没有更多的括号,如下面的命令输出:
# add disk -pool <name> { -diskid <diskid> | -diskid auto } [-fx]
command = [ ['add'], ['disk'], ['-pool <name>'], ['-diskid <diskid>', '-diskid auto'], ['', '-fx']]
print(list(itertools.product(*command)))
print(len(list(itertools.product(*command))))
输出:
[('add', 'disk', '-pool <name>', '-diskid <diskid>', ''),
('add', 'disk', '-pool <name>', '-diskid <diskid>', '-fx'),
('add', 'disk', '-pool <name>', '-diskid auto', ''),
('add', 'disk', '-pool <name>', '-diskid auto', '-fx')]
4
我怎样才能得到预期的结果? :c
【问题讨论】:
-
not :( 我只是想从一个字符串(命令字符串)中知道有多少种可能性(基于语法命令的规则,如 [ ... ],{ ... })
标签: python combinatorics