2015-04-24 35 views
2

我在Python代码中遇到了以下问题。默认参数不起作用

的错误是:

Traceback (most recent call last): File "cmd.py", line 16, in <module> 
    func(b="{cmd} is entered ...") # Error here 
File "cmd.py", line 5, in func 
    exceptMsg = b.format(errStr=errStr, debugStr=debugStr) 
KeyError: 'cmd' 

代码:

import re 

def func(errStr = "A string", b = "{errStr}\n{debugStr}"): 
    debugStr = "Debug string" 
    exceptMsg = b.format(errStr=errStr, debugStr=debugStr) 
    raise ValueError(exceptMsg) 

try: 
    ''' 
    Case 1: If user invokes func() like below, error produced. 
    Possible explanation: Paramter b of func() is looking keyword 
    'errStr' further down in func() body, but I am passing it keyword 
    'cmd' instead. What to change to make the code work? 
    ''' 
    #cmd = "A crazy string"    # Comment, make code pass 
    #func(b="{cmd} is entered ...")  # Error here 

    # Case 2: If user invokes func() like below, OK. 
    errStr = "A crazy string" 
    func(b="{errStr} is entered") 

except ValueError as e: 
    err_msg_match = re.search('A string is entered:', e.message) 
    print "Exception discovered and caught!" 

1)如果函数接口FUNC()是保留的,要改变什么码?

2)如果我必须修改函数接口,我该如何去做一个干净的代码更改?

+0

输出(续): ---------------- $ python cmd.py 回溯(最近一次调用最后一次): 文件“cmd.py”,第16行, func(b =“{cmd} is entered ...”)#此处出错 文件“cmd.py”,第5行,在func 除外Msg = b.format(errStr = errStr,debugStr = debugStr) KeyError:'cmd' $ python cmd.py 发现并捕获到异常! – user1972031

+0

你会得到什么错误? –

+2

请把它写入你的问题,格式正确。 –

回答

3

b.format(errStr=errStr, debugStr=debugStr)只通过errStrdebugStr替换占位符。如果b包含任何其他占位符变量,它将会失败。

您有:

b = "{cmd} is entered ..." 

没有什么可以匹配{cmd}

如果你想通过cmdfunc,你可以用keyword arguments做到这一点:

def func(errStr = "A string", b = "{errStr}\n{debugStr}", **kwargs): 
    debugStr = "Debug string" 
    exceptMsg = b.format(errStr=errStr, debugStr=debugStr, **kwargs) 
    raise ValueError(exceptMsg) 

而作为使用:

func(b="{cmd} is entered ...", cmd="A crazy string")