1

I'am trying to write a function which can parse 1 or 2 ip addresses & a searchterm.

For example: ./system.py 172.16.19.152,172.16.19.153 model\ name
Output:
Search term: model name
Server: 172.16.19.152
Results:
Processor 0:
model name  : Intel(R) Core(TM) i5-3210M CPU @ 2.50GHz
Server: 172.16.19.153
Results:
Processor 0:
model name  : Intel(R) Core(TM) i5-3210M CPU @ 2.50GHz

How can i get this usage instructions with argparse:

 usage:./system.py {IP}[,{IP}] {SEARCH\ TERM}
2
  • You can use argparse to parse a list of string separated by commas, then scan the list to get either one or two IPs. The search term is basic argparse. Commented Jul 25, 2016 at 9:58
  • Optionally you can also you nargs to limit the number of IPs Commented Jul 25, 2016 at 10:00

2 Answers 2

2
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('ips',metavar='IP',nargs='+')
parser.add_argument('search_term',metavar='SEARCH\\ TERM',nargs=1)

The metavar keyword will be used in the usage text for your program. The double backslash is used for escaping the single backslash character for your SEARCH\ TERM argument. By calling parser.parse_args() the returning dictionary will contain your arguments parsed which can be reached like this:

args = parser.parse_args()
args.ips
args.search_term

The nargs keyword will tell the number of this kind of argument to be passed to your program.

+ means at least one, 1 means exactly one argument to be passed.

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

Comments

0

To resume, you can use argparse as below.

parser = argparse.ArgumentParser()
parser.add_argument('--IP', nargs=2)
parser.add_argument('--TERM', nargs=1)

Comments

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.