python-fire
python-fire copied to clipboard
Passing an argument multiple times
How can add argument multiple times?
For example, in the multiply example, how to pass arbitrary number of integers with flags like this -
python calculate.py multiply -x 1 -x 2 -x 3 6
To specify an argument multiple times, you can use the argparse library in Python. Here is an example of how you can use argparse to parse a list of integers from the command-line arguments and multiply them:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-x', action='append', type=int, help='an integer')
args = parser.parse_args()
result = 1
for x in args.x:
result *= x
print(result)
You can then call the script with the following command:
python calculate.py multiply -x 1 -x 2 -x 3
This will output 6, which is the result of multiplying 1 * 2 * 3.
Also, note that the -x argument is specified as an append action, which means that it can be specified multiple times on the command line and the values will be stored in a list. The type parameter specifies that the values should be converted to integers.
Hope this Helps.