简体   繁体   English

在python中将IP列表解析为argparse

[英]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. 我想执行一个Python脚本,该脚本使用几种IP地址来执行某些操作。 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']] [['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'] [ '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 如何将多个字符串解析为argparse但在一个参数下,以便将其分隔在列表中
  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. 您想要的是仅使用nargs=+键入str (默认值),然后将地址显示为进程的真实,独立参数。

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. 这是使用nargs=+的预期方式,其中type参数定义每个列表元素的元素类型。

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. 如果你真的想使用的IP1,IP2格式,你需要提供一个自定义的检查功能,如图这里 ,那么这将需要使用字符串操作,包括你必须处理那么所有角落的情况下手动拆分输入,使用建议的方法时argparse会自动对其进行处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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