How to add command line arguments with flags in Python3?

Viewed 51101

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?

3 Answers

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
Related