Python 参数解析 : diiference between -o and --option

标签 python argparse

我试图理解 argparse 包,但我真的找不到这个非常简单的问题的答案:

  • 添加参数时-a--argument有什么区别?

有时,我会在一个 add_argument() 中找到两者,如下所示:

parser.add_argument(
        "-f", "--file",
        help="file path"
        )

最佳答案

如果两者都指定,则 argparse 将以长格式('argument')而不是短格式('a')存储值。它将推断目的地,因此“--foo-bar”将存储在 foo_bar 中。

您可以将短格式混合在一起并使用单个连字符 (-af),但与某些 *NIX 命令不同,顺序很重要:如果您的参数需要一个值 (-f filename) 那么参数必须作为短格式参数组的最后一个参数出现:

cmd -af my_file   # works
cmd -fa my_file   # does not work

将此与允许 tar -cfC myfile.tar ./directory 的怪物 tar(1) 进行比较,并将正确地将其排序为逻辑上等同于 tar -c -f myfile.tar -C ./directory.此外,一些长格式允许在指定选项 tar -cf myfile.tar 时使用“=”,而不是 tar -c --file=myfile.tar。不能在短格式上使用“=”。

幸运的是,python argparse 不关心'='。使用与否,短格式或长格式。

# All equivalent:
  cmd -af=my_file
  cmd -a -f my_file
  cmd -a -fmy_file
  cmd -afmy_file
  cmd --file my_file -a
  cmd --file=my_file -a

重要吗?正如另一个答案所暗示的那样,长格式有助于提高可读性。简短的形式可以让您的高级用户更快乐。

关于Python 参数解析 : diiference between -o and --option,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44555973/

相关文章:

python pandas 过滤 true、false 和两者的列

Python-Pandas : How to sort a pivot table maintaining one column grouped

如果文件名已经存在,Python 将文件复制到新目录并重命名

python - 当我将 isin 与 Dask 数据帧一起使用时,会引发 NotImplementedError

python - 需要使用 argparse 的 python 命令行参数的帮助

python - 从 Pandas 中的字符串中删除字符

python-3.x - python argparse在使用特定选项时忽略其他选项

python - 不要在最后一个位置参数之后解析选项

python - 导入的 python 模块覆盖选项解析器

python - 子类化 argparse.ArgumentParser 会产生奇怪的行为