【发布时间】:2014-03-04 17:29:42
【问题描述】:
我正在创建一个 python 脚本并解析我需要的参数: 该脚本将接受三个参数,只有一个始终是强制性的,第二个将仅根据第一个的某些值是强制性的,第三个可能会出现也可能不会出现。 这是我的尝试:
class pathAction(argparse.Action):
folder = {'remote':'/path1', 'projects':'/path2'}
def __call__(self, parser, args, values, option = None):
args.path = values
print "ferw %s " % args.component
if args.component=='hos' or args.component=='hcr':
print "rte %s" % args.path
if args.path and pathAction.folder.get(args.path):
args.path = pathAction.folder[args.path]
else:
parser.error("You must enter the folder you want to clean: available choices[remote, projects]")
def main():
try:
# Arguments parsing
parser = argparse.ArgumentParser(description="""This script will clean the old component files.""")
parser.add_argument("-c", "--component", help="component to clean", type=lowerit, choices=["hos", "hcr", "mdw", "gui"], required=True)
parser.add_argument("-p", "--path", help="path to clean", action = pathAction, choices = ["remote", "projects"])
parser.add_argument("-d", "--delete", help="parameter for deleting the files from the filesystem", nargs='*', default=True)
args = parser.parse_args()
如果效果很好,除了一种情况:如果我有 -c 它应该抱怨,因为没有 -p 但它没有 你能帮我吗? 谢谢
【问题讨论】:
标签: python parsing python-2.7 argparse