I am trying to use argparse to parse command line arguments. Here is my code:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import argparse
def create_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--allow_ips', nargs='*')
return parser
if __name__ == '__main__':
parser = create_parser()
namespace = parser.parse_args()
When the script is executed like this, argparse complains about unrecognized arguments.
./prog.py --allow_ips=192.168.0.10 192.168.0.11 192.168.0.12
But when the script is executed like this, argparse is satisfied.
./prog.py --allow_ips 192.168.0.10 192.168.0.11 192.168.0.12
How should I change my code so '=' can be used in the argument list?
According to the argparse documentation, passing * in the nargs argument means
All command-line arguments present are gathered into a list.
When you invoke your program without the equal sign, all three IP addresses are considered part of the --allow_ips argument; they will be available to your program in a list.
When you invoke your program with the equal sign, only the first IP address is considered part of the --allow_ips argument. argparse then tries to parse the second and third IP addresses. But it cannot because your program does not take any positional arguments. So argparse raises an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With