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?
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”.
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.
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.
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
))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With