3

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?

2

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. In my case, the arguments are passed to bash script (entry point). I found that the quotes around the list of IP-addresses are lost. I went through the arguments in the loop, added quotes and wrote it in one line, and then passed it as parameters to my program on the python. Sorry for my english.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.