victor gatto
victor gatto

Reputation: 61

Creating command line switches in python

For example, sqlmap uses python sqlmap.py -h.

This command above lists all available switches in sqlmap, and -h is a switch itself.

When you are creating a python tool for use in terminal, what is the basic method to create a switch?

A hello world example would be most appreciative!

Upvotes: 5

Views: 788

Answers (2)

Cairnarvon
Cairnarvon

Reputation: 27762

The command line arguments a program was started with are exposed as a list of strings in sys.argv, with sys.argv[0] being the program name.

Other, older standard-library modules to help deal with them include getopt and optparse. You should indeed be using argparse, though.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121484

These are command line options. You can use the stdlib argparse module for that.

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print args.accumulate(args.integers)

Upvotes: 8

Related Questions