【问题标题】:Python Fire hyphen vs underscorePython Fire连字符与下划线
【发布时间】:2020-10-16 14:37:14
【问题描述】:

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

  • 猫的名字
  • 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 不能在变量名中包含连字符。

【问题讨论】:

  • 不确定 fireargparse 会自动将破折号转换为下划线。

标签: python python-fire


【解决方案1】:

看起来它可以与连字符或下划线一起使用,可能是因为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

Fire 文档中也注明了 here

要实例化一个Building,然后运行climb_stairs函数,下面的命令都是有效的:

$ 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"

您会注意到连字符和下划线(-_)在成员名称和标志名称中可以互换。

但是,生成的帮助文本似乎确实要求带有下划线的标志:

> 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 (包含在标准库中)或click(我个人最喜欢的)。 Here 是 Fire 自称的福利清单;如果您的用例更复杂,另一个库可能会更好。

【讨论】:

  • 是的,就是这样,我只是在阅读文档时失败了,我想这会发生 ^^ 非常感谢您的回答/时间 :)
【解决方案2】:

不确定Fire 模块,但我确实有一个python 命令行应用程序,我们在其中使用nameofcat 类型语法。我将一个包含多达 17 个 aplhabets 的单词作为参数传递给脚本,并且我不使用任何连字符或下划线。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-20
    • 2021-11-28
    • 2012-01-04
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    相关资源
    最近更新 更多