使用“%"运算符的字符串格式的可选键? [英] Optional keys in string formats using '%' operator?

查看:36
本文介绍了使用“%"运算符的字符串格式的可选键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 字符串格式中使用可选键 使用%"运算符?我在 Python 2.7 中使用 logging API,所以我不能使用 高级字符串格式.

我的问题如下:

<预><代码>>>>导入日志>>>FORMAT = '%(asctime)-15s %(message)s %(user)s'>>>logging.basicConfig(格式=格式)>>>logging.warning("它适用于:", extra={'user': 'me'})2016-08-29 11:24:31,262 适用于:我>>>logging.warning("它不起作用!")回溯(最近一次调用最后一次):...密钥错误:'用户'从文件 ,第 1 行记录

如果缺少,我希望 user 有一个空字符串.我该怎么做?

我尝试使用 defaultdict,但失败了:

<预><代码>>>>进口藏品>>>额外 = collections.defaultdict(unicode)>>>logging.warning("它不起作用!", extra=extra)回溯(最近一次调用最后一次):...密钥错误:'用户'从文件 ,第 1 行记录

相比之下,使用 Jinja2,我们可以:

<预><代码>>>>进口jinja2>>>jinja2.Template('name: {{ name }}, email: {{ email }}').render(name="me")你的名字:我,电子邮件:'

=> 这里也不例外,只是一个空字符串(用于电子邮件").

解决方案

A) defaultdict 方法工作正常,但前提是直接使用.

<预><代码>>>>进口藏品>>>dd=collections.defaultdict(str)>>>dd['k'] = 22>>>'%(k)s %(nn)s' % dd'22'

<小时>

B) 日志函数的 extra 参数按照文档中的描述使用,即不是直接如上所示.这就是为什么使用 defaultdict 而不是常规的 dict 没有区别的原因.

<块引用>

第三个关键字参数是额外的,可用于传递一个用于填充 LogRecord 的 dict 的字典为具有用户定义属性的日志事件创建.

<小时>

C) 您可以使用日志过滤器来处理丢失的额外数据:

导入日志类用户过滤器:def过滤器(自我,记录):尝试:记录用户除了属性错误:record.user = ''返回真FORMAT = '%(asctime)-15s %(message)s %(user)s'logging.basicConfig(格式=格式)logging.getLogger().addFilter(UserFilter())logging.warning("它适用于:", extra={'user': 'me'})logging.warning("它不起作用!")# DATE TIME 它不起作用!<不适用>

任何带有 filter 方法的类都可以.它可以就地修改记录,并且必须返回 True 以接受记录或返回 False 以将其过滤掉.

Is is possible to have optional keys in string formats using '%' operator? I’m using the logging API with Python 2.7, so I can't use Advanced String Formatting.

My problem is as follow:

>>> import logging

>>> FORMAT = '%(asctime)-15s %(message)s %(user)s'
>>> logging.basicConfig(format=FORMAT)

>>> logging.warning("It works for:", extra={'user': 'me'})
2016-08-29 11:24:31,262 It works for: me

>>> logging.warning("It does't work!")
Traceback (most recent call last):
  ...
KeyError: 'user'
Logged from file <input>, line 1

I want to have an empty string for user if missing. How can I do that?

I tried with a defaultdict, but it fails:

>>> import collections
>>> extra = collections.defaultdict(unicode)
>>> logging.warning("It does't work!", extra=extra)
Traceback (most recent call last):
  ...
KeyError: 'user'
Logged from file <input>, line 1

By contrast, with Jinja2, we can do:

>>> import jinja2
>>> jinja2.Template('name: {{ name }}, email: {{ email }}').render(name="me")
u'name: me, email: '

=> no exception here, just an empty string (for "email").

解决方案

A) The defaultdict approach works fine, but only if used directly.

>>> import collections
>>> dd=collections.defaultdict(str)
>>> dd['k'] = 22
>>> '%(k)s %(nn)s' % dd
'22 '


B) The extra argument to a log function is used as described in the docs, i.e. not directly as shown above. That's why using a defaultdict instead of a regular dict does not make a difference.

The third keyword argument is extra which can be used to pass a dictionary which is used to populate the dict of the LogRecord created for the logging event with user-defined attributes.


C) You can use a logging filter to take care of the missing extra data:

import logging

class UserFilter:
    def filter(self, record):
        try:
            record.user
        except AttributeError:
            record.user = '<N/A>'
        return True

FORMAT = '%(asctime)-15s %(message)s %(user)s'
logging.basicConfig(format=FORMAT)
logging.getLogger().addFilter(UserFilter())

logging.warning("It works for:", extra={'user': 'me'})

logging.warning("It doesn't work!")
# DATE TIME It doesn't work! <N/A>

Any class with a filter method is fine. It can modify the record in-place and it must return True for accepting the record or False for filtering it out.

这篇关于使用“%"运算符的字符串格式的可选键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆