Fred Bongers
Fred Bongers

Reputation: 267

Python Argparse usage instructions

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}

Upvotes: 1

Views: 407

Answers (2)

Gábor Fekete
Gábor Fekete

Reputation: 1358

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.

Upvotes: 2

Abhinav
Abhinav

Reputation: 1042

To resume, you can use argparse as below.

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

Upvotes: 0

Related Questions