2

I'd like to use my program this way:

pythonScript -f filename

But if I forgot -f, I still want to get the filename.

So I want this "pythonScript filename" also work (->I can get the file name from args.fileName or from handling the exception)

I know this must be easy, I just can not find a way to do it. Anyone can help me out? Thanks

import argparse parser = argparse.ArgumentParser(prog='PROG') parser.add_argument('-f', action='store', dest='fileName', default = None, type=str, help='The file name') try: args = parser.parse_args() except: print "xxx" 
2
  • That's expected and good. -* is a flag, and option - it's not required. Plus, you never stated it should be required, quite the contrary, you even provided a default value. Commented Aug 26, 2011 at 15:21
  • oh, I mean I still want to get the filename if I forgot -f. sorry about the confusion Commented Aug 26, 2011 at 15:24

1 Answer 1

3

If you want -f to be required, you can make it that way with argparse. Just include "required = True" inside of the add_argument function.

Remember that required option is contradictory. It's not suggested to make options required, but sometimes helpful. If the option is not given, then the destination remains the None value (or it gets assigned whatever default value you've given, which is None in your example).

EDIT: Just saw your edit and I understand what you're asking now. optparse makes this simpler IMO. It seems for positional arguments with argparse, you need to use add_argument.

There's really no easy way to have argparse do it for you. You can simulate it a little bit creatively with the following:

parser = argparse.ArgumentParser() parser.add_argument('file', nargs='?') parser.add_argument('-f', dest='file_opt') args = parser.parse_args() if args.file_opt: args.file = args.file_opt 

Basically, if there's a file option given, it overwrites the positional argument.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, but I actually want -f to be optional, please see my updated question

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.