开发者

Python: how to handle the exceptions of argparse?

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开发者_如何学Python', dest='fileName',
    default = None, type=str, help='The file name')

try:
    args = parser.parse_args()
except:
    print "xxx"


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜