寻找在python中提供命令行参数的最佳方法,其中某些参数对于某些选项是必需的,而某些参数对于其他选项是必需的 [英] looking for best way of giving command line arguments in python, where some params are req for some option and some params are req for other options

查看:101
本文介绍了寻找在python中提供命令行参数的最佳方法,其中某些参数对于某些选项是必需的,而某些参数对于其他选项是必需的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试首次发送命令行参数.条件是一个选项需要一个参数,而其他参数则需要其他参数.下面的代码看起来需要一些优化:

Hi i am trying to send command line arguments for first time. The condition is that one parameter is required for one option and for others other parameter.(looking for user friendly). The below code looks need some optimization:

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()

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

Hope you get my required params for required options from code. Please let me know for detailed explanation on requirements

推荐答案

此脚本的变体可以运行,并清除了几处内容.它使用choices控制选项值.它在其他add_argument调用中省略了不必要的参数.它简化了parse_args帖子的逻辑.确实不需要help,因为总是有-h选项,但我将其作为选择.由于它不在action词典中,因此它一直到最后.

This variation on your script runs, and cleans up several things. It uses choices to control the options values. It omits unnecessary parameters in the other add_argument calls. It simplifies the post parse_args logic. help isn't really needed since there is always the -h option, but I included it as a choice. It falls through to the end because it is not in the action dictionary.

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进行所有检查.

This version replaces the options choices with subparsers. config and jobid become required arguments for the appropriate subparsers. I use parents to conveniently define the required mix and match. Now argparse does all the checking.

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)

这篇关于寻找在python中提供命令行参数的最佳方法,其中某些参数对于某些选项是必需的,而某些参数对于其他选项是必需的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆