0

嗨,我第一次尝试发送命令行参数。条件是一个选项需要一个参数,其他参数需要一个参数。(寻找用户友好的)。下面的代码看起来需要一些优化:

import argparse
parser = argparse.ArgumentParser(description='Usage options.')
parser.add_argument('-o','--options',help='Options available: run,rerun,kill, resume,           suspend',required=True)
parser.add_argument('-c', '--config',help='config file input',type=file,required=False)
parser.add_argument('-j', '--id',help='id of the job',type=str,required=False)
args = parser.parse_args()
action_arg = list()
action_arg.append(args.options)
action = {'run': start_run,
          'rerun': start_rerun,
          'kill': kill_job,
          'resume': resume_job,
          'suspend': suspend_job,
          'get_run': get_run,
          'get_component': get_component,
          'help': print_help}.get('-'.join(action_arg))

if action:
    conf_file = str(args.config)
    jobid = str(args.jobid)
    if args.options == "run":
        if conf_file == "None":
            print "Job configuration is needed to start a run and job id is not needed"
            sys.exit(2)
    elif args.options == "rerun":
        if conf_file == "None" or jobid == "None":
            print "Job configuration and jobid is needed to start a rerun."
            sys.exit(2)
    else:
        if jobid == "None":
            print "Jobid is needed to perform %s action on job and configuration is not needed." %args.options
            sys.exit(2)
    action(conf_file, jobid)
else:
    print "Usage Error:"
    print_help()

希望您从代码中获得所需选项的所需参数。请让我知道有关要求的详细说明

4

1 回答 1

0

脚本的这种变体运行,并清理了几件事。它用于choices控制选项值。add_argument它在其他调用中省略了不必要的参数。它简化了发布parse_args逻辑。help并不是真的需要,因为总是有-h选项,但我把它作为一个选择。它一直到最后,因为它不在action字典中。

import argparse
import sys
class Stub(object):
    def __init__(self,s):
        self.s = s
    def __call__(self,conf_file, jobid):
        print self.s, conf_file, jobid
parser = argparse.ArgumentParser(description='Usage options.')
parser.add_argument('-o','--options', choices=('run','rerun','kill', 'resume', 'suspend','help'),required=True)
parser.add_argument('-c', '--config',help='config file input')
# optionals normally not required; 'file' not valid type
# argparse.FileType will open the file
parser.add_argument('-j', '--jobid',help='id of the job')
# str is the default type
args = parser.parse_args()
# action_arg = [args.options]
action = {'run': Stub('start_run'),
          'rerun': Stub('start_rerun'),
          'kill': Stub('kill_job'),
          'resume': Stub('resume_job'),
          'suspend': Stub('suspend_job'),
          #'get_run': get_run, # not in choices
          #'get_component': get_component,
          #'help': print_help,
          }.get(args.options)  # what's with the '-'.join?

if action:
    if args.options == "run":
        if args.config is None: # proper test for None
            print "Job configuration is needed to start a run and job id is not needed"
            sys.exit(2)
    elif args.options == "rerun":
        if args.config is None or args.jobid is None:
            print "Job configuration and jobid is needed to start a rerun."
            sys.exit(2)
    else:
        if args.jobid is None:
            print "Jobid is needed to perform %s action on job and configuration is not needed." %args.options
            sys.exit(2)
    action(args.config, args.jobid)
else:
    print "Usage Error:"
    parser.print_help()

这个版本options用子解析器替换了选项。 configjobid成为适当的子解析器的必需参数。我parents用来方便地定义所需的混合搭配。现在argparse进行所有检查。

import argparse
class Stub(object):
    def __init__(self,s):
        self.s = s
    def __call__(self,conf_file, jobid):
        print self.s, conf_file, jobid

conf_parent = argparse.ArgumentParser(add_help=False)
conf_parent.add_argument('-c', '--config',help='config file input',required=True)
job_parent = argparse.ArgumentParser(add_help=False)
job_parent.add_argument('-j', '--jobid',help='id of the job',required=True)

parser = argparse.ArgumentParser(description='Usage options.')
parser.set_defaults(config=None, jobid=None) # put default value in namespace
sp = parser.add_subparsers(dest='options')
sp.add_parser('run',parents=[conf_parent])
sp.add_parser('rerun',parents=[conf_parent, job_parent])
sp.add_parser('kill',parents=[job_parent])
sp.add_parser('resume',parents=[job_parent])
sp.add_parser('suspend',parents=[job_parent])
args = parser.parse_args()

action = {'run': Stub('start_run'),
          'rerun': Stub('start_rerun'),
          'kill': Stub('kill_job'),
          'resume': Stub('resume_job'),
          'suspend': Stub('suspend_job'),
          }.get(args.options)
action(args.config, args.jobid)
于 2013-08-20T22:46:29.557 回答