Tiago Oliveira
Tiago Oliveira

Reputation: 47

Python argparser optional arg that requires other arguments

I have searched the internet and I couldn't find if it is possible to make an argument with python argparser package that is optional but when it is choosen it needs aeguments.

For better understanding I will explain in code so you guys can understand easier.

My goal is to have a database with all my websites and apps I have registered in and store there the site or platform, mail, user and the password. And I wanted to create some optional arguments such as:

Python manageaccounts.py --add steam mail user pass

That is just an example but I think it makes it much more understandable. Basically Instead of "--add" I want to have like "--delete" and a "--change" argument as well. With that I want to say that I don t know how to make an argument optional that when it is choosen it requires another argument, in this case I choose "--add" and to add a new line to my database I need a "site" a "mail" "user" and "pass", and I want to make "--add" optional and when it is choosen to make site mail user and pass required

If anyone didn't understand what I want to know is to know how I can make an argument require another arguments.

Upvotes: 1

Views: 103

Answers (1)

Michal
Michal

Reputation: 1310

Sounds like want you want is a subparser

Here is an example:

import argparse

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='subparser')

add = subparsers.add_parser("add")
add.add_argument('steam')
add.add_argument('mail')
add.add_argument('user')
add.add_argument('password')

delete = subparsers.add_parser("delete")
delete.add_argument('user')

args = parser.parse_args()

if args.subparser == 'add':
    print("Called add with arguments", args.user, args.mail, args.steam, args.password)
elif args.subparser == 'delete':
     print("Called delete with arguments", args.user)
else:
    print("Unknown option")


Upvotes: 1

Related Questions