如何在Python中实现可选的位置参数

时间:2017-03-23 14:08:35

标签: python python-2.7 parameters optional

我有一个Python 2.7脚本返回一些数据。它还需要命令行位置参数:
filename.py -ip 172.17.12.12 -username admin

到目前为止,我已经使用以下函数(testargv.py)计算了4个参数:

def getopts(argv):
    opts = {}
    while argv:
        if argv[0][0] == '-':
            opts[argv[0]] = argv[1]
            argv = argv[2:]
        else:
            argv = argv[1:]
    return opts

myargs = getopts(argv)
if '-ip' in myargs:
    ip = myargs['-ip']
elif 'username' in myargs:
    username = myargs['-username']
elif 'password' in myargs:
    password = myargs['-password']
elif 'outfile' in myargs:
    outfile = myargs['-outfile']

此单独的.py文件已导入到现有项目(来自testargv import getopts),在执行脚本之前,会发生以下情况:

ip = getopts(argv)['-ip']
username = getopts(argv)['-username']
password = getopts(argv)['-password']
outfile = getopts(argv)['-outfile']

我想让“outfile”成为可选项。因此用户无需输入,默认应为
os.getcwd()+'\'+'Select.log'

我尝试将以下内容添加到testargv.py:

elif 'outfile' not in myargs:
    outfile = os.getcwd() + '\\' + 'Select.log'

或将以下内容添加到程序代码中:

if getopts(argv)['-outfile']:
    outfile = getopts(argv)['-outfile']
else:
    outfile = cwd + '\\' + 'Select.log'

但没有-outfile的程序仍然失败:      outfile = getopts(argv)[' - outfile']
KeyError:' - outfile'

1 个答案:

答案 0 :(得分:1)

一些建议:

  1. 尝试使用https://docs.python.org/2/library/argparse.html
  2. 如果没有那么:
    • 多次调用var data = {"base":"ZAR","date":"2017-03-22","rates":{"AUD":0.10349,"BGN":0.14369,"BRL":0.24601,"CAD":0.10622,"CHF":0.078716,"CNY":0.54686,"CZK":1.9852,"DKK":0.54641,"GBP":0.063765,"HKD":0.61677,"HRK":0.54432,"HUF":22.714,"IDR":1058.3,"ILS":0.29021,"INR":5.1943,"JPY":8.8215,"KRW":88.906,"MXN":1.5201,"MYR":0.35154,"NOK":0.67198,"NZD":0.1128,"PHP":3.9874,"PLN":0.31457,"RON":0.33495,"RUB":4.603,"SEK":0.69874,"SGD":0.111,"THB":2.7496,"TRY":0.28768,"USD":0.079399,"EUR":0.07347}} var keys = Object.keys(data.rates); var half = Math.ceil(keys.length/2); for(var i = 0;i<half;i++) console.log("First half", keys[i], data.rates[keys[i]]); for(var i =half;i<keys.length;i++) console.log("Second half", keys[i], data.rates[keys[i]]);,调用一次并将结果保存在变量中
    • 考虑使用getopts(argv)的{​​{3}}方法,如果您要求的密钥不在字典中,则返回dict
  3. 所以只需改变:

    None

    成:

    if getopts(argv)['-outfile']:
       outfile = getopts(argv)['-outfile']
    else:
       outfile = cwd + '\\' + 'Select.log'
    

    或者:

    outfile = getopts(argv).get('-outfile')
    if not outfile:
       outfile = cwd + '\\' + 'Select.log'