very new to working with argparse and the cmd line. I've started to build a parser that allows for a front-end user to enter in data via the cmd terminal. The parser is calling the API() class that I have created (which creates the SQLALCHEMY session and etc.), example shown here:
class API(object):
def __init__(self):
# all the session / engine config here
def create_user(self, username, password, firstname, lastname, email):
new_user = User(username, password, firstname, lastname, email)
self.session.add(new_user)
self.session.commit()
print(username, firstname, lastname)
def retrieve_user(self, username, firstname, lastname):
# code here ... etc .
to implement in the CMD file here:
def main():
parser = argparse.ArgumentParser(prog='API_ArgParse', description='Create, Read, Update, and Delete (CRUD) Interface Commands')
subparsers = parser.add_subparsers(
title='subcommands', description='valid subcommands', help='additional help')
api = API() # calling the API class functions/engine
# Create command for 'user'
create_parser = subparsers.add_parser('create_user', help='create a user')
create_parser.add_argument('username', type=str, help='username of the user')
create_parser.add_argument('password', type=str, help='password')
create_parser.add_argument('firstname', type=str, help='first name')
create_parser.add_argument('lastname', type=str, help='last name')
create_parser.add_argument('email', type=str, help='email address')
#args = parser.parse_args() <--EDIT:removed from here and placed on bottom
api.create_user(args.username, args.password, args.firstname, args.lastname, args.email)
# Retrieve command for 'user'
retrieve_parser = subparsers.add_parser('retrieve_user', help='retrieve a user')
retrieve_parser.add_argument('username', type=str, help='username')
retrieve_parser.add_argument('firstname', type=str, help='first name')
retrieve_parser.add_argument('lastname', type=str, help='last name')
api.retrieve_user(args.username, args.firstname, args.lastname)
NEW EDIT/ADDITION OF args = parser.parse_args() to use both commands to reflect comments below.
args = parser.parse_args()
print(args)
if __name__ == '__main__':
main()
and so on...
My problem is that the terminal is NOT printing the help command for the new parsers (e.g. retrieve_parser, update_parser, etc.). Do I have to create a "args = parser.parse_arg()" per section? Secondly, do I create a "args = create_parser.parse_args()" in-place of just "parser.parse..." I notice they print two different things on the terminal.
Any clarification about where to place the parse_arg() method (taking into consideration the use of the API() function) is greatly appreciated!!