R
R
Roman Sokolov2018-02-18 08:44:22
Python
Roman Sokolov, 2018-02-18 08:44:22

How to parse all command line parameter values ​​in python?

Hello.
I am writing a script that is launched by a third-party application with parameters already set in a certain format.
An example script using the argparse library:

#!/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()

    print (namespace)

Script call examples:
python ./script.py --allow_ips=
python ./script.py --allow_ips=192.160.0.10
python ./script.py --allow_ips=192.160.0.10 192.160.0.11 192.160.0.12

Those. the number of values ​​for the allow_ips parameter can be 0 or more.
The first two calls are executed correctly, the third call throws an exception:

error: unrecognized arguments: 192.160.0.11 192.160.0.12

If you use a space instead of the "=" character, then all parameters are transferred correctly, but the third-party application transfers the parameters in this format.
How can I tell the library to use the correct delimiter in such a call?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2018-02-18
@InterVi

I don't know about the delimiter, try using parse_known_args .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question