1

I am trying to write a python program that will provide some github features in cli like creating issues, creating repos, creating PRs, etc.

I came up with something like github create issue --title <title> --description <description> --user <user> --repo <repo>

I used argparse for this purpose

import argparse
parser = argparse.parser()
parser.add_argument('create', 
                    options=['issue', 'repo', 'pull')
                    action='store')
parser.add_argument('--title', action="store", type=str)
parser.add_argument('--description', action="store", type=str)
parser.add_argument('--user', action="store")
parser.add_argument('--repo')

parser.parse_args('create issue --title title --description desc --user user --repo repo')

I used the options --title and --descriptions to get the information in keyword form.

While options are meant to be optional, but according to my style of parsing:

  • If create is issue then --title, --description, --user, --repo are required.

What will be the right approach of parsing the command github create issue --title title --description desc --user user --repo repo ?

Meet
  • 294
  • 3
  • 8

1 Answers1

0

First a couple of tweaks:

parser.add_argument('--title', action="store", type=str)

can be simplified to

parser.add_argument('--title')

since this action and type are the defaults. You do this with --repo.

args = parser.parse_args()

reads from the commandline and puts the values in the args namespace.

args = parser.parse_args(['issue --title title --description desc --user user --repo repo'].split())

can be used to test this parser with a simulated list of strings.

Note that I dropped create.

parser.add_argument('create', choices=['issue', 'repo', 'pull'))

defines a positional that will be put in args as args.create. The strings it accepts are the choices (not options). An alternative is to use --create; in which case it behaves like the other arguments, only with a limit in accepted values.

If you want to require some arguments for a specific value, you need to do the testing after parsing, e.g.

if args.create in ['issue']:
    if args.title is None or args.user is None:
       parser.error('title and user required with issue')

This is almost a duplicate of a recent How can I make Python argparse to have dependency which was also closed as a duplicate.

An alternative is to use subparsers. But you can read about those in the docs and previous [argparse] questions.

Try these ideas and come back with a new question.

You'll have to write a custom usage and/or help paragraphs to describe the constrains to your users.

Community
  • 1
  • 1
hpaulj
  • 221,503
  • 14
  • 230
  • 353