Python multiple user arguments to a list

。_饼干妹妹 提交于 2019-12-11 04:31:59

问题


I've got not words to thank you all of you for such great advice. Now everything started to make sense. I apologize for for my bad variable naming. It was just because I wanted to quickly learn and I wont carry out such practices when I write the final script with my own enhancements which will be posted here.

I want to go an another step further by passing the values we've isolated (ip,port,and name) to a template. I tried but couldn't get it right even though I feel close. The text I want to construct looks like this. (

          Host Address:<IP>:PORT:<1>
          mode tcp
          bind <IP>:<PORT> name <NAME>

I have tried this within the working script provided by rahul.(I've edited my original code abiding stackexchange's regulations. Please help out just this once as well. Many thanks in advance.

#!/usr/bin/python
import argparse
import re
import string

p = argparse.ArgumentParser()
p.add_argument("input", help="input the data in format ip:port:name", nargs='*')  
args = p.parse_args()
kkk_list = args.input 

def func_three(help):
    for i in help:
        print(i)

for kkk in kkk_list:
    bb = re.split(":|,", kkk) 
    XXX=func_three(bb)
for n in XXX:
    ip, port, name = n
    template ="""HOST Address:{0}:PORT:{1}
              mode tcp
              bind {0}:{1} name {2}"""
       sh = template.format(ip,port,name)
       print sh
orignial post:--

Beginner here. I wrote the below code and it doesn't get me anywhere.

#!/usr/bin/python
import argparse
import re
import string

p = argparse.ArgumentParser()
p.add_argument("INPUT")  
args = p.parse_args()
KKK= args.INPUT
bb=re.split(":|,", KKK)

def func_three(help):
    for i in help:
        #print help
        return help

#func_three(bb[0:3])
YY = var1, var2, var3 = func_three(bb[0:3])
print YY

The way to run this script should be "script.py :". i.e: script.py 192.168.1.10:80:string 172.25.16.2:100:string

As you can see if one argument is passed I have no problems. But when there are more arguments I cant determine how to workout the regexes and get this done via a loop.

So to recap, this is how i want the output to look like to proceed further.

192.168.1.10
80
name1

172.25.16.2
100
name2

If there are better other ways to achieve this please feel free to suggest.


回答1:


Please name your variable with respect to context. You will need to use nargs=* for accepting multiple arguments. I have added the updated code below which prints as you wanted.

#!/usr/bin/python
import argparse
import re
import string

p = argparse.ArgumentParser()
p.add_argument("input", help="input the data in format ip:port:name", nargs='*')  
args = p.parse_args()
kkk_list = args.input # ['192.168.1.10:80:name1', '172.25.16.2:100:name3']

def func_three(help):
    for i in help:
        print(i)

for kkk in kkk_list:
    bb = re.split(":|,", kkk) 
    func_three(bb)
    print('\n')

# This prints
# 192.168.1.10
# 80
# name1


# 172.25.16.2
# 100
# name3

Updated Code for new requirement

#!/usr/bin/python
import argparse
import re
import string

p = argparse.ArgumentParser()
p.add_argument("input", help="input the data in format ip:port:name", nargs='*')  
args = p.parse_args()
kkk_list = args.input # ['192.168.1.10:80:name1', '172.25.16.2:100:name3']


def printInFormat(ip, port, name):
    formattedText = '''HOST Address:{ip}:PORT:{port} 
                        mode tcp 
                        bind {ip}:{port} name {name}'''.format(ip=ip, 
                                                                port=port, 
                                                                name=name)
    textWithoutExtraWhitespaces =  '\n'.join([line.strip() for line in formattedText.splitlines()])
    # you can break above thing
    # text = ""
    # for line in formattedText.splitlines():
    #       text += line.strip()
    #       text += "\n" 

    print(formattedText)


for kkk in kkk_list:
    ip, port, name = re.split(":|,", kkk)

    printInFormat(ip, port, name)


# HOST Address:192.168.1.10:PORT:80
# mode tcp
# bind 192.168.1.10:80 name name1
# HOST Address:172.25.16.2:PORT:100
# mode tcp
# bind 172.25.16.2:100 name name3



回答2:


I would say what you are doing could be done more simply. If you want to split the input whenever a colon appears you could use:

#!/usr/bin/python
import sys

# sys.argv is the list of arguments you pass when you run the program
# but sys.argv[0] is the actual program name
# so you want to start at sys.argv[1]
for arg in sys.argv[1:]:
    listVar = arg.split(':')
    for i in listVar:
        print i
    # Optionally print a new line
    print



回答3:


Bad variable names aside, if you want to use argparse (which I think is a good habit, even if it is somewhat more complex initially) you should use the nargs='+' option:

#!/usr/bin/env python

import argparse
import re
import string

p = argparse.ArgumentParser()
p.add_argument("INPUT", nargs='+')  
args = p.parse_args()
KKK= args.INPUT

def func_three(help):
    for i in help:
        #print help
        return help

for kkk in KKK:
    bb=re.split(":|,", kkk)
    #func_three(bb[0:3])
    YY = var1, var2, var3 = func_three(bb[0:3])
    print YY



回答4:


If you look at the documentation for argparse, you'll notice that there's an nargs argument you can pass to add_argument, which allows you to group more than one input.

For example:

p.add_argument('INPUT', nargs='+')

Would make it so that there is a minimum of one argument, but all arguments will be gathered into a list.

Then you can go through each of your inputs like this:

args = p.parse_args()
for address in args.INPUT:
    ip, port = address.split(':')


来源:https://stackoverflow.com/questions/43512392/python-multiple-user-arguments-to-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!