[英]How to pass a list/array as argument to python fire?
I have function like this -我有这样的功能-
def my_func(my_list_arg=["one", "two"]):
Which I'm trying to call from command line using python-fire
.我试图使用python-fire
从命令行调用它。
I have tried several ways -我尝试了几种方法-
Attempt 1:尝试1:
fire_runner.py my_func [one, two]
Results in two separate arguments "[one"
and "two]"
.产生两个单独的参数"[one"
和"two]"
。
Attempt 2:尝试2:
fire_runner.py my_func ["one", "two"]
which has the same result.结果相同。
Attempt 3:尝试 3:
fire_runner.py my_func [\"one\", \"two\"]
same result.同样的结果。
Your list will first be parsed by the command line shell.您的列表将首先由命令行 shell 解析。 This means you need to force it as a single argument.这意味着您需要将其强制为单个参数。 There are many ways to do this:有很多方法可以做到这一点:
No space: [one,two]
没有空格: [one,two]
Escape the space: [one,\ two]
逃离空间: [one,\ two]
Quotes: "[one, two]"
.引号: "[one, two]"
。
Note that you could modify your function to take a list of arguments using the following syntax:请注意,您可以使用以下语法修改函数以获取参数列表:
def my_func(*args):
The name args
here is convention, but it is just a variable name, so it can be anything.这里的名称args
是约定俗成的,但它只是一个变量名,所以它可以是任何东西。 This will allow you to call your function as这将允许您将您的函数称为
fire_runner.py my_func one two
逗号对我有用后没有保留任何空格。
fire_runner.py my_func [one,two]
Adding this answer just for a special case.仅针对特殊情况添加此答案。
given that your function is like this:鉴于您的功能是这样的:
def my_func(dates: List[str] = []):
...
In case you need to send list of dates (or any combination of numbers and characters) from the CLI, the following WON'T work.如果您需要从 CLI 发送日期列表(或数字和字符的任意组合),以下将不起作用。
fire_runner.py my_func --dates 2021-09-20,
fire_runner.py my_func --dates "[2021-09-20]"
fire_runner.py my_func --dates [2021-09-20]
In all the above cases, dates will be read as one string instead of list of strings.在上述所有情况下,日期将被读取为一个字符串而不是字符串列表。 For proper reading of list of strings you can use the following.为了正确阅读字符串列表,您可以使用以下内容。
fire_runner.py my_func --dates "[\"2021-09-20\"]"
fire_runner.py my_func --dates "[\"2021-09-20\", \"2021-09-76\"]"
Fire converts a comma-separated digit string to tuple as follows: Fire 将逗号分隔的数字字符串转换为元组,如下所示:
fire_runner.py my_func 1,2,3
and for a comma-separated string you can use:对于逗号分隔的字符串,您可以使用:
fire_runner.py my_func \'2021-2\',\'20212-3\',\'2023-4\'
为一个元素列表添加特殊的极端情况解决方案,因为上述语法似乎不起作用(列表被解析为以[
开头的字符串):
fire_runner.py my_func "['one']"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.