Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add command line arguments with flags in Python3?

Tags:

I have to input the parameters from the command line i.e username, password, and database name. I know how to do that without using flags, by using sys.argv like below:

##Test.py
hostname = str(sys.argv[1])
username = str(sys.argv[2])
password = str(sys.argv[3])

def ConnecttoDB():
    try:
        con=sql.connect(host=hostname, user= username, passwd= password)
        print ('\nConnected to Database\n')

# If we cannot connect to the database, send an error to the user and exit the program.
    except sql.Error:
        print ("Error %d: %s" % (sql.Error.args[0],sql.Error.args[1]))
        sys.exit(1)

    return con   

So, it could be run as:

$test.py DATABASE USERNAME PASWORD

But the problem is that I have to use 'flags'. So, the script could be run like this:

$test.py -db DATABSE -u USERNAME -p PASSWORD -size 20

How can I use flags to take arguments from the command line?

like image 887
Atul Kakrana Avatar asked Jul 22 '12 22:07

Atul Kakrana


People also ask

How do you add 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 you pass arguments in Python terminal?

In Python, arguments are passed to a script from the command line using the sys package. The argv member of sys ( sys. argv ) will store all the information in the command line entry and can be accessed inside the Python script. Python's getopt module can also be used to parse named arguments.

What is Flag in Python command?

flags defines a distributed command line system, replacing systems like getopt() , optparse , and manual argument processing. Rather than an application having to define all flags in or near main() , each Python module defines flags that are useful to it.


1 Answers

The python 3 library includes 3 modules for parsing the command line thus nothing extra to add to your setup.

The one you should use is argparse

import argparse
parser = argparse.ArgumentParser()

#-db DATABSE -u USERNAME -p PASSWORD -size 20
parser.add_argument("-db", "--hostname", help="Database name")
parser.add_argument("-u", "--username", help="User name")
parser.add_argument("-p", "--password", help="Password")
parser.add_argument("-size", "--size", help="Size", type=int)

args = parser.parse_args()

print( "Hostname {} User {} Password {} size {} ".format(
        args.hostname,
        args.username,
        args.password,
        args.size
        ))
like image 54
mmmmmm Avatar answered Oct 11 '22 13:10

mmmmmm