python - Should we use options to get information that is not optional but we do that to make it look more intuitive? -
i trying write python program provide github features in cli creating issues, creating repos, creating prs, etc.
i came github create issue --title <title> --description <description> --user <user> --repo <repo>
i used argparse 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 options --title , --descriptions information in keyword form.
while options meant optional, according style of parsing:
- if
createissue--title,--description,--user,--reporequired.
what right approach of parsing command github create issue --title title --description desc --user user --repo repo ?
first couple of tweaks:
parser.add_argument('--title', action="store", type=str) can simplified to
parser.add_argument('--title') since action , type defaults. --repo.
args = parser.parse_args() reads commandline , puts values in args namespace.
args = parser.parse_args(['issue --title title --description desc --user user --repo repo'].split()) can used test parser simulated list of strings.
note dropped create.
parser.add_argument('create', choices=['issue', 'repo', 'pull')) defines positional put in args args.create. strings accepts choices (not options). alternative use --create; in case behaves other arguments, limit in accepted values.
if want require arguments specific value, need testing after parsing, e.g.
if args.create in ['issue']: if args.title none or args.user none: parser.error('title , user required issue') this duplicate of recent how can make python argparse have dependency closed duplicate.
an alternative use subparsers. can read in docs , previous [argparse] questions.
try these ideas , come new question.
you'll have write custom usage and/or help paragraphs describe constrains users.
Comments
Post a Comment