2

So here's my question: I want my program to accept only one specific value, without which it wouldn't go ahead.

I know the 'choices' keyword can be used as answered here: Allowing specific values for an Argparse argument

But I wanted to ask if there is another way, because if I tell it the choice, it will give it up in help.

I could give my function as if condition to process it but was hoping to use argparse.

Also if someone could suggest suggestions to this: my argument is basically a path directory, is there a specific option for that which I might use?

Or do you guys think that going with 'choices' is my best option. Beginner level programmer here.

New Guy
  • 383
  • 2
  • 12
  • What do you mean by "if I tell it the choice, it will give it up in help"? – martineau Oct 07 '18 at 17:09
  • 4
    So you want a password? `argparse` isn't really the way to implement that. – chepner Oct 07 '18 at 17:10
  • `metavar` can hide the choices in the help, but won't hide them in the error message. You may have to do your own acceptance testing after parsing. – hpaulj Oct 07 '18 at 17:25
  • If you want to use your custom function as a condition, you proably want to use custom [type](https://docs.python.org/3/library/argparse.html#type) for an argument, a callable which parses an argument – Eir Nym Oct 07 '18 at 22:35

2 Answers2

0

ArgeParse: You can pass argument with "-year" followed by argument value. Only in this format an argument will be accepted.

import os
import argparse
from datetime import datetime


def parse_arguments():
    parser = argparse.ArgumentParser(description='Process command line arguments.')
    parser.add_argument('-year', '--yearly', nargs = '*', help='yearly date', type=date_year)

    return parser.parse_args()


def date_year(date):
    if not date:
        return

    try:
        return datetime.strptime(date, '%Y')
    except ValueError:
        raise argparse.ArgumentTypeError(f"Given Date({date}) not valid")



def main():
    parsed_args = parse_arguments()

if __name__ == "__main__":
main()
Asad Manzoor
  • 1,355
  • 15
  • 18
0

You don't need argparse for this.

import sys, logging
if not 'mellor' in sys.argv[1:]:
    logging.error('Speak, friend, and enter')
    sys.exit(1)
tripleee
  • 175,061
  • 34
  • 275
  • 318