【发布时间】: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 不能在变量名中包含连字符。
【问题讨论】:
-
不确定 fire 但argparse 会自动将破折号转换为下划线。
标签: python python-fire