gpt4 book ai didi

Python Fire 连字符与下划线

转载 作者:行者123 更新时间:2023-12-03 19:02:33 33 4
gpt4 key购买 nike

python包Fire对于从命令行启动 python 脚本非常有用。一件常见的事情是有由多个单词组成的参数,例如可以用 3 种通用方式编写的 cat 的名称:

  • nameofcat
  • name_of_cat
  • 猫名

  • 虽然第一个几乎与所有内容兼容,但在 bash 中应避免使用第二个( Should command line options in POSIX-style operating systems be underscore style? ),在 python 中应避免使用第三个( Why does python disallow usage of hyphens within function and variable names? )。
    这里的问题是,默认情况下,fire 将从 python 代码中获取参数名称,这意味着如果我的 python 代码如下所示:
    脚本.py:
    import fire
    def main(name_of_cat='Steve'):
    print(f'The name of the cast is {name_of_cat}')
    if __name__ == '__main__':
    fire.Fire(main)
    然后从命令行(或从 bash 脚本)调用它,可以这样做
    python script.py --name_of_cat Bob
    这是我目前使用它的方式,但这感觉不是最佳的。知道这里的最佳实践是什么吗?
    PS: python script.py --name-of-cat Bob这是不可能的,因为 python 在变量名中不能有连字符。

    最佳答案

    看起来它适用于连字符或下划线,可能是因为 this line of code .使用您的脚本:

    > python .\script.py --name_of_cat Bob
    The name of the cast is Bob
    > python .\script.py --name-of-cat Bob
    The name of the cast is Bob
    这也被注意到 here在 Fire 文档中:

    To instantiate a Building and then run the climb_stairs function, the following commands are all valid:

    $ python example.py --name="Sherrerd Hall" --stories=3 climb_stairs 10
    $ python example.py --name="Sherrerd Hall" climb_stairs --stairs_per_story=10
    $ python example.py --name="Sherrerd Hall" climb_stairs --stairs-per-story 10
    $ python example.py climb-stairs --stairs-per-story 10 --name="Sherrerd Hall"

    You'll notice that hyphens and underscores (- and _) are interchangeable in member names and flag names.


    但是,生成的帮助文本似乎要求带有下划线的标志:
    > python .\script.py -h
    INFO: Showing help with the command 'script.py -- --help'.

    NAME
    script.py

    SYNOPSIS
    script.py <flags>

    FLAGS
    --name_of_cat=NAME_OF_CAT
    我的建议是,如果您正在为自己制作一个快速脚本,Fire 非常棒,但如果您制作的是分布式或更复杂的东西,最好使用更可配置的框架,例如 argparse (包含在 stdlib 中)或 click (我个人最喜欢的)。 Here是 Fire 自述的好处 list ;如果您的用例更复杂,另一个库可能会更好。

    关于Python Fire 连字符与下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64391263/

    33 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com