I can't seem to figure out how to call the add_user()
function in the script and pass it all the arguments needed. If I do this
if args.adduser:
add_user(username, account, groups)
it doesn't find the adduser
Namespace
.
AttributeError: 'Namespace' object has no attribute 'adduser'
However, if I add this
parser_adduser.set_defaults(func=add_user)
it appears to execute the add_user()
function, but doesn't pass it any of the arguments.
def parse_args():
helptext = 'Script to Add, Delete, Update AWS Users'
parser = argparse.ArgumentParser(description=helptext,
prog='aws-IAM-user.py',
usage='%(prog)s [position] [-u] [optional]',
conflict_handler='resolve',)
parser.add_argument('-v', '--version',
dest='version')
subparsers = parser.add_subparsers(title='Main commands',
help='MORE INFO: [COMMAND] -help')
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument('-u', '--username',
dest='username',
action='store',
help='list a single user or multiple users, '
'seperated by space',
nargs='+',
required=True)
parent_parser.add_argument('-a', '--account',
dest='account',
action='store',
nargs='+',
help='Specify Account(s).'
' Default is to use all available')
# 'Add User Parsers'
parser_adduser = subparsers.add_parser('adduser',
parents=[parent_parser],
help='adduser -u USER -a ACCOUNT -g GROUP.'
' Passwords are auto-gen')
parser_adduser.add_argument('-g', '--group',
dest='groups',
nargs='+',
help='specify group(s) seperated by space')
parser_adduser.set_defaults(func=add_user)
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
config = ConfigParser.RawConfigParser()
config.read(AWS_CONFIG_FILE)
username = args.username
account = args.account
I don't know if I am just daft, but I can't seem to figure out how to call the script using adduser
and pass all the flags while using the subparser
feature that I want to use so badly.
答案 0 :(得分:0)
I think you're misunderstanding what it means to add a subparser. When you add a subparser, if the subparser is selected on the commandline, that subparser's arguments will be added to the namespace. Then the standard way of interacting with the commandline is to create an entry point for each subparser that accepts the args namespace as an argument. e.g. suppose you want to have an adduser
and a removeuser
subparser. they you might do something like:
def add_user(args):
"""Entry point for add_user."""
account = args.account
username = args.username
...
def remove_user(args):
"""Entry point for remove_user."""
remove_user_argument = args.remove_user_argument
...
subparsers = parser.add_subparsers()
add_user_parser = subparsers.add_parser('adduser')
add_user_parser.add_argument(...)
add_user_parser.set_defaults(func=add_user)
add_user_parser = subparsers.add_parser('removeuser')
add_user_parser.add_argument(...)
add_user_parser.set_defaults(func=remove_user)
args = parser.parse_args()
args.func(args)