How to add command line arguments with flags in Python3?
Asked Answered
G

3

31

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?

Grippe answered 22/7, 2012 at 22:57 Comment(0)
G
17

First of all thanks to Mark for 'argparse' code. I have figured out the way to take arguments from command line specified by flags. I am pasting the code below which uses a modified 'Mark' code and a small module that shows how to use the arguments collected via commandline:

import argparse

parser = argparse.ArgumentParser()

#-db DATABASE -u USERNAME -p PASSWORD -size 20000
parser.add_argument("-host", "--hostname", dest = "hostname", default = "xyz.edu", help="Server name")
parser.add_argument("-db", "--database", dest = "db", default = "ding_dong", help="Database name")
parser.add_argument("-u", "--username",dest ="username", help="User name")
parser.add_argument("-p", "--password",dest = "password", help="Password")
parser.add_argument("-size", "--binsize",dest = "binsize", help="Size", type=int)

args = parser.parse_args()

print( "Hostname {} db {} User {} Password {} size {} ".format(
        args.hostname,
        args.db,
        args.username,
        args.password,
        args.binsize
        ))
def ConnectToDB():
    print ('Trying to connect to mySQL server')
    # Try to connect to the database
    try:
        con=sql.connect(host=args.hostname, user= args.username, passwd= args.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

One of my concerns was how to use variables from arguments to the code. For that two things need to be done

  1. Add 'dest' to the add_argument line e.x. dest ="username" which means the value collected from the command line will be assigned to variable 'username'
  2. Whenever an you use such command line assigned variables from 'dest' just add 'args' before variable e.x con=sql.connect(host=args.hostname, user= args.username, passwd= args.password)
Grippe answered 23/7, 2012 at 18:52 Comment(1)
You accepted your own problem solution, whereas @Mark did provide you an answer to your question. I'm not sure if this is very kind...Cachet
C
103

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 DATABASE -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
        ))
Conni answered 22/7, 2012 at 23:18 Comment(1)
Thanks for your reply and code. The problem I am facing now is that my code is giving error 'Undefined variables' for variables defined in above code. This is because, earlier their values were explicitly mentioned inside the script but after including the code by Mark, the values are not recognized by script. In short how do I make script take values of variables from 'argparse' module. For ex. earlier in script: hostname = 127.0.0.1, username = xyz and password = abc but now these were replaced by code above (by Mark) therefore script now says 'Undefined Variables'.Grippe
G
17

First of all thanks to Mark for 'argparse' code. I have figured out the way to take arguments from command line specified by flags. I am pasting the code below which uses a modified 'Mark' code and a small module that shows how to use the arguments collected via commandline:

import argparse

parser = argparse.ArgumentParser()

#-db DATABASE -u USERNAME -p PASSWORD -size 20000
parser.add_argument("-host", "--hostname", dest = "hostname", default = "xyz.edu", help="Server name")
parser.add_argument("-db", "--database", dest = "db", default = "ding_dong", help="Database name")
parser.add_argument("-u", "--username",dest ="username", help="User name")
parser.add_argument("-p", "--password",dest = "password", help="Password")
parser.add_argument("-size", "--binsize",dest = "binsize", help="Size", type=int)

args = parser.parse_args()

print( "Hostname {} db {} User {} Password {} size {} ".format(
        args.hostname,
        args.db,
        args.username,
        args.password,
        args.binsize
        ))
def ConnectToDB():
    print ('Trying to connect to mySQL server')
    # Try to connect to the database
    try:
        con=sql.connect(host=args.hostname, user= args.username, passwd= args.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

One of my concerns was how to use variables from arguments to the code. For that two things need to be done

  1. Add 'dest' to the add_argument line e.x. dest ="username" which means the value collected from the command line will be assigned to variable 'username'
  2. Whenever an you use such command line assigned variables from 'dest' just add 'args' before variable e.x con=sql.connect(host=args.hostname, user= args.username, passwd= args.password)
Grippe answered 23/7, 2012 at 18:52 Comment(1)
You accepted your own problem solution, whereas @Mark did provide you an answer to your question. I'm not sure if this is very kind...Cachet
K
0

first, install cli-args-system with:

linux: pip3 install cli-args-system
windows: pip install cli-args-system

after:

from cli_args_system import Args

#for dont try to convert the host
args = Args(convert_numbers=False)

hostname = args.flag_str('h','hostname','host')
username = args.flag_str('u','user','username','password')
password = args.flag_str('p','password')


print(f'host: {hostname}')
print(f'username: {username}')
print(f'password: {password}')

try:

python3 teste.py -h 1234 -user foo -p bar
-> 
host: 1234
username: foo
password: bar
Kra answered 5/1, 2022 at 15:44 Comment(1)
Please elaborate on why you choose cli_args_systems args passing over the build in argparse (docs), because using a build in solution seems to be preferredBillboard

© 2022 - 2024 — McMap. All rights reserved.