所以,我有这个问题.我得到了元组(1,2,3),我应该用字符串格式打印.例如.
tup = (1,2,3)
print "this is a tuple %something" % (tup)
Run Code Online (Sandbox Code Playgroud)
这应该用括号打印元组表示,比如
这是一个元组(1,2,3)
但我得到了TypeError: not all arguments converted during string formatting.
我能在世界上做到这一点吗?有点失去了这里,如果你们可以指出我正确的方向:)
我正在使用prospector来检查我的代码.Pylint返回了logging-not-lazy有关我的调试消息的警告.
Line: 31
pylint: logging-not-lazy / Specify string format arguments as logging function parameters (col 16) Line: 42
pylint: logging-not-lazy / Specify string format arguments as logging function parameters (col 12)
Run Code Online (Sandbox Code Playgroud)
我的代码是:
logging.debug("detect mimetypes faild because %s" % e )
Run Code Online (Sandbox Code Playgroud)
我如何修复logging-not-lazypylint?
我在一个项目中遇到性能问题,并将其缩小到某些日志行。似乎即使我的日志记录工具高于正在记录的行的级别,也可以计算f字符串。
考虑以下示例以演示该问题:
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('MyLogger')
class MyClass:
def __init__(self, name: str) -> None:
self._name = name
def __str__(self) -> str:
print('GENERATING STRING')
return self._name
c = MyClass('foo')
logger.debug(f'Created: {c}')
Run Code Online (Sandbox Code Playgroud)
运行此示例时,我将在屏幕上打印“ GENERATING STRING”,表示__str__即使将我的日志记录级别设置为INFO,并且日志行为,该方法也正在运行DEBUG。
据我今天所知,解决方案是使用以下vs f字符串。
logger.debug('Created: %s', c)
Run Code Online (Sandbox Code Playgroud)
我现在脑子里发生了三件事。
我很想知道其他人在这种情况下会做什么。是%s最好的(最现代的)办法?如上所述,有没有更现代的方式记录我的日志?
我有很多代码需要更新(修复),我希望与现代最佳实践保持一致。
使用 Python 记录变量的推荐方法logging是什么,为什么更好?
旧式插值:
apple = "green"
logger.debug("apple is %s", apple)
Run Code Online (Sandbox Code Playgroud)
或者
新风格 .format()
logger.debug("apple is {}".format(apple))
Run Code Online (Sandbox Code Playgroud)
我听说插值是首选的,因为它只评估要打印的字符串,但我还没有验证它是否真的很重要。
使用一个简单的自定义异常类定义为:
class MyError(Exception):
pass
Run Code Online (Sandbox Code Playgroud)
这个电话:
foo = 'Some more info'
raise MyError("%s: there was an error", foo)
Run Code Online (Sandbox Code Playgroud)
pylint 给出:
异常参数表明字符串格式可能是有意的
pylint(raising-format-tuple)
这个消息是什么意思?