简体   繁体   中英

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!

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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