Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating command line switches in python

Tags:

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!

like image 744
victor gatto Avatar asked Apr 20 '13 12:04

victor gatto


People also ask

How do you create a command line argument in Python?

To add arguments to Python scripts, you will have to use a built-in module named “argparse”. As the name suggests, it parses command line arguments used while launching a Python script or application. These parsed arguments are also checked by the “argparse” module to ensure that they are of proper “type”.

How do I create a command line tool?

Create a file index. js in the root of the project. This will be the main entry of the CLI tool that will initialize the commands it will have. NOTE: If you are using Windows for development, make sure that the line end character is set to LF instead of CRLF or the tool will not work.

Can Python run CMD?

Using the IDLE we can write and also run our programs. But we can also run python programs on CMD or command prompt as CMD is the default command-line interpreter on Windows. But there's a need to set up the environment variable in windows to use python on the command-line.


1 Answers

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)
like image 158
Martijn Pieters Avatar answered Oct 01 '22 03:10

Martijn Pieters