python argparse to handle arbitrary numeric options (like HEAD(1))

Is there a way to trick argparse into accepting arbitrary numeric arguments like HEAD(1) ?

head -5 test.txt

is equivalent to

head -n 5 test.txt

My current approach is to use parse_known_args() and then handle the remainder, but I'd wish there was something a tad more elegant.


agrparse和optparse都不支持这一点。


对的,这是可能的:

#!/usr/bin/env python
# coding: utf-8

from argparse import ArgumentParser

parser = ArgumentParser(description='Argparse with numeric arguments')
parser.add_argument('-0', action='store_true', help='null separator')
args = parser.parse_args()
print vars(args)['0']

作为使用vars(args)['0] @ vault的答案的替代方法,您也可以使用args.__dict__['0']

链接地址: http://www.djcxy.com/p/10624.html

上一篇: Android ANR SurfaceView

下一篇: python argparse处理任意数字选项(如HEAD(1))