2012-06-25 91 views
1

是否可以將* args傳遞給string.format?我有以下功能:在Python中將* args傳遞給string.format?

@classmethod 
def info(cls, component, msg, *args): 
    """Log an info message""" 
    cls.__log(cls.Level.INFO, component, msg, args) 

@classmethod 
def __log(cls, level, component, msg, *args): 
    """Log a message at the requested level""" 
    logging.getLogger("local").log(level, " - ".join([component, msg.format(args)])) 

當我試圖單元測試與LogCapture我得到如下:

def test_logWithArgs(self): 
    Logger.level(Logger.Level.INFO) 
    with LogCapture(level=Logger.Level.INFO) as lc: 
     Logger.info("MyComponent", "{0}", "TestArg") 
     lc.check(("local", "INFO", "MyComponent - TestArg")) 


AssertionError: Sequence not as expected: 

same: 
() 

first: 
(('local', 'INFO', 'MyComponent - TestArg'),) 

second: 
(('local', 'INFO', "MyComponent - (('TestArg',),)"),) 
+0

我覺得你有你的答案 - 但我要請您看看logging.Formatter設施 –

回答

5

我想你想要做的是

msg.format(*args) 
+0

這將導致以下'((「本地」,「INFO」,「MyComponent的 - (‘TestArg’ ,)「),)' – Graeme

+0

你也必須改變它的info():'cls .__ log(cls.Level.INFO,component,msg,* args)' –

+0

你是對的 - 謝謝。 – Graeme

1

是它是。

>>> a=(1,2,3,4) 
>>> "{0}{1}{2}{3}".format(*a) 
'1234'