我在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)如果必须修改功能接口,如何进行干净的代码更改?

最佳答案

b.format(errStr=errStr, debugStr=debugStr)仅传递errStrdebugStr来替换占位符。如果b包含任何其他占位符变量,它将失败。

你有:

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


没有匹配项{cmd}

如果要将cmd传递给func,则可以使用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")

09-25 19:38