我已通读 Python argparse documentation好几次了,肯定漏掉了一些巨大的东西。我试图在我的 cli 工具中添加类似于 makefile 的语法,但是尽管 --help
标志向我显示了预期的行为,但它的执行却出错了:
test.py
import argparse
import os
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
make_subparser = subparsers.add_parser("make")
make_subparser.add_argument("update", action="store_false", help="Runs all make targets")
make_subparser.add_argument("clean", action="store_false", help="Cleans up everything done previously")
args = parser.parse_args()
if args.update:
os.system("touch test.txt")
elif args.clean:
os.system("rm test.txt")
else:
print("Bad args, see: python test.py make --help.")
if __name__ == "__main__":
main()
然后在我的终端中:
$> python test.py make --help
usage: test.py make [-h]
positional arguments:
update Runs all make targets
$> python test.py make update
usage: test.py [-h] {make} ...
test.py: error: unrecognized arguments: update
$> # this should make a file
$>
$> python test.py make clean
usage: test.py [-h] {make} ...
test.py: error: unrecognized arguments: clean
$> # this should delete the file
如果我将 action="store_false"
替换为 action="store_true"
,效果很好,但是有十几个 make 命令,所以我只想运行用户在 cli 中添加的一个,如果他们尝试输入更多内容,它应该退出。
最佳答案
在 POSIX(以及 POSIX 相邻)世界中, bool 参数被处理为标志,这些标志通过命令行作为 --argument
传递。你想要的不是 bool 参数(这也不是 Make 对待它们的方式),它只是可变数量的位置参数,即具有 arity *
:
make_subparser.add_argument('targets', nargs='*')
这最接近 Make 的运作方式。但是,从命令行来看,它看起来更像是您实际想要的嵌套 subcommands .
关于python - 将 argparse.subparser 与 bool 值一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60266653/