在Python中将* args传递给string.format?

时间:2012-06-25 20:43:51

标签: python logging args

是否可以将* 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',),)"),)

2 个答案:

答案 0 :(得分:5)

我认为你想要做的是

msg.format(*args)

答案 1 :(得分:1)

是的。

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