简体   繁体   中英

Parsing a list of IPs to argparse in python as string

I want to execute a python script that does something with several IP adresses. These adresses can be given via commad line.

I use the following command for parsing:

parser.add_argument('--IP',dest='Adresses',help='some Ips', 
default=['192.168.2.15','192.168.2.3'],type=list,nargs='+')

However, when I run the script via command like the following:

python script.py --IP 192.168.2.15,192.168.2.3

It splits up the string after every character, the same behaviour occurs if I use a space instead of a comma, so if I print it out the following output happens

[['1', '9', '2', '.', '1', '6', '8', '.', '2', '.', '1', '5'], ['1', '9', '2', '.', '1', '6', '8', '.', '2', '.', '3']]

What I desire to have is:

['192.168.2.15','192.168.2.3']

like described in the default parameters

So two things I do not get to work here:

  1. How can I parse several strings to argparse but under one argument, so that it gets seperated in a list
  2. How can I stop the splitting up by characters

Thank you for your help

What you want is type str (the default) with just nargs=+ and then presenting the addresses as real, separated arguments to the process.

so:

parser.add_argument('--IP', dest='Adresses', help='some Ips', 
                    default=['192.168.2.15','192.168.2.3'], nargs='+')

Will result in the following when called with two arguments:

parser.parse_args(['--IP', '123.45', '123.34'])
Namespace(Adresses=['123.45', '123.34'])

This would translate to the following command line call:

python script.py --IP 123.45 123.34

This is the intended way of using nargs=+ , where the type parameter defines the element type of each list element.

In case you would really want to use the IP1,IP2 format, you would need to provide a custom checking function as shown here , which would then need to manually split the input using string manipulation, including all the corner cases you have to handle then, which are automatically handled by argparse when using the proposed way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM