2015-04-24 31 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")