在调试时,我们经常会看到如下的print语句:
print x # easy to type, but no context
print 'x=',x # more context, harder to type
12
x= 12
Run Code Online (Sandbox Code Playgroud)
如何编写一个函数来获取变量或变量的名称并打印其名称和值?我只对调试输出感兴趣,这不会被合并到生产代码中.
debugPrint(x) # or
debugPrint('x')
x=12
Run Code Online (Sandbox Code Playgroud)
Cir*_*四事件 25
Python 3.8 f字符串=语法
已经到了!
#!/usr/bin/env python3
foo = 1
bar = 2
print(f"{foo=} {bar=}")
Run Code Online (Sandbox Code Playgroud)
输出:
foo=1 bar=2
Run Code Online (Sandbox Code Playgroud)
“ 提交https://github.com/python/cpython/commit/9a4135e939bc223f592045a38e0f927ba170da32 “使用'='添加f字符串调试”中添加。哪些文件:
f-strings now support = for quick and easy debugging
-----------------------------------------------------
Add ``=`` specifier to f-strings. ``f'{expr=}'`` expands
to the text of the expression, an equal sign, then the repr of the
evaluated expression. So::
x = 3
print(f'{x*9 + 15=}')
Would print ``x*9 + 15=42``.
Run Code Online (Sandbox Code Playgroud)
因此它也适用于任意表达式。真好!
Ble*_*der 20
你可以使用eval:
def debug(variable):
print variable, '=', repr(eval(variable))
Run Code Online (Sandbox Code Playgroud)
或者更一般地说(它实际上在调用函数的上下文中工作并且不会中断debug('variable'),但仅在CPython上):
from __future__ import print_function
import sys
def debug(expression):
frame = sys._getframe(1)
print(expression, '=', repr(eval(expression, frame.f_globals, frame.f_locals)))
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
>>> x = 1
>>> debug('x + 1')
x + 1 = 2
Run Code Online (Sandbox Code Playgroud)
Azi*_*lto 13
例如使用f'{var = }'Python3.8 中的最新特性:
>>> a = 'hello'
>>> print(f'{a = }')
a = 'hello'
Run Code Online (Sandbox Code Playgroud)
import inspect
import re
def debugPrint(x):
frame = inspect.currentframe().f_back
s = inspect.getframeinfo(frame).code_context[0]
r = re.search(r"\((.*)\)", s).group(1)
print("{} = {}".format(r,x))
Run Code Online (Sandbox Code Playgroud)
这不适用于所有版本的python:
检查当前帧()
CPython 实现细节: 此函数依赖于解释器中的 Python 堆栈帧支持,不能保证在 Python 的所有实现中都存在。如果在没有 Python 堆栈框架支持的实现中运行,则此函数返回 None。
刚刚开发了@Padraic Cunningham 的答案来获取任意数量的变量。我喜欢这个方法,因为它的工作原理就像print(x1, x2, x3)- 不需要将 var 名称包装在''.
import inspect
import re
def prinfo(*args):
frame = inspect.currentframe().f_back
s = inspect.getframeinfo(frame).code_context[0]
r = re.search(r"\((.*)\)", s).group(1)
vnames = r.split(", ")
for i,(var,val) in enumerate(zip(vnames, args)):
print(f"{var} = {val}")
x1 = 1
x2 = 2
x3 = 3
prinfo(x1, x2, x3)
Run Code Online (Sandbox Code Playgroud)
输出是:
x1 = 1
x2 = 2
x3 = 3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27345 次 |
| 最近记录: |