1

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.

Tiago Oliveira
  • 47
  • 1
  • 12
  • did you try 'nargs=?' previously discussed https://stackoverflow.com/a/4480202/7548672 –  May 09 '20 at 02:43
  • I started today learning about this package so I don't know much as I don't know what that is but if u could explain me i would appreciate a lot! – Tiago Oliveira May 09 '20 at 02:45
  • 'nargs' specifies the number of command-line arguments that should be consumed. One can specify a direct value nargs= 3, a variable number of arguments nargs=*, a single value which can be optional args='?' or args='+' like * but requires a single argument. Read about it more here: https://docs.python.org/3/library/argparse.html#nargs –  May 09 '20 at 03:12
  • Oh I understand know thanks a lot dude! – Tiago Oliveira May 09 '20 at 09:45

1 Answers1

1

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")


Michal
  • 1,300
  • 2
  • 14
  • 22