python中scripts空的_在Python中解析空选项

I have an application that allows you to send event data to a custom script. You simply lay out the command line arguments and assign what event data goes with what argument. The problem is that there is no real flexibility here. Every option you map out is going to be used, but not every option will necessarily have data. So when the application builds the string to send to the script, some of the arguments are blank and python's OptionParser errors out with "error: --someargument option requires an argument"

Being that there are over 200 points of data, it's not like I can write separate scripts to handle each combination of possible arguments (it would take 2^200 scripts). Is there a way to handle empty arguments in python's optionparser?

解决方案

Sorry, misunderstood the question with my first answer. You can accomplish the ability to have optional arguments to command line flags use the callback action type when you define an option. Use the following function as a call back (you will likely wish to tailor to your needs) and configure it for each of the flags that can optionally receive an argument:

import optparse

def optional_arg(arg_default):

def func(option,opt_str,value,parser):

if parser.rargs and not parser.rargs[0].startswith('-'):

val=parser.rargs[0]

parser.rargs.pop(0)

else:

val=arg_default

setattr(parser.values,option.dest,val)

return func

def main(args):

parser=optparse.OptionParser()

parser.add_option('--foo',action='callback',callback=optional_arg('empty'),dest='foo')

parser.add_option('--file',action='store_true',default=False)

return parser.parse_args(args)

if __name__=='__main__':

import sys

print main(sys.argv)

Running from the command line you'll see this:

# python parser.py

(, [])

# python parser.py --foo

(, [])

# python parser.py --foo bar

(, [])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值