在python / ipython中将函数变量转储到工作空间 [英] Dump function variables to workspace in python/ipython
问题描述
在使用python / ipython repl进行开发和调试时,我想在某个时候将函数中的所有局部变量转储到工作区以查看发生了什么。假设我有一个函数
When developing and debugging with python/ipython repl, at some point I'd like to dump all the local variables in a function to the workspace to see what's going on. Suppose I have a function
def func():
a = "blablabla"
b = 1234
c = some_calculation_of_a_and_b(a,b)
dump_to_workspace(a,b,c) # is this possible?, or even more preferable:
dump_all_local_variables_to_workspace() # is this possible?
我希望能在python / ipython中运行它:
I hope to be able to run this in python/ipython:
>>> func()
>>> print a
"blablabla"
>>> print b
1234
>>> print c
some_calculated_value
我知道两种选择:(1)从函数返回变量[不好,因为我不想弄乱返回值],以及(2)将数据保存到磁盘上的文件[不方便,因为它涉及可能有大量数据的磁盘I / O]。但是大多数时候都不那么方便。有没有办法直接实现转储?
I know two alternatives: (1) return the variables from the function [not good because I don't want to mess up with return value], and (2) save the data to a file on the disk [not convenient because it involve disk I/O with possibly large amount of data]. But those aren't as convenient most of the times. Is there a way to achieve the dumping directly?
提前多多谢谢!
推荐答案
要扩展我上面的评论,这里是pdb的快速介绍:
To expand on my comment above, here's a quick intro to pdb:
import pdb
def func():
a = "blablabla"
b = 1234
c = some_calculation_of_a_and_b(a,b)
pdb.set_trace()
运行:
python program.py
解释器将停在pdb.set_trace()行,允许您观察 a $ c $的值c>,
b
和 c
。
The interpreter will then stop at the pdb.set_trace() line allowing you to observe the values of a
,b
and c
.
停止时,您可以通过键入以下内容来打印局部变量的值:
While stopped, you can print the values of the local variables by typing:
p a
p b
等。可以通过在pdb提示符下键入?
来获取pdb中的完整命令列表。 此处是图书馆文档的链接。
etc. A full list of commands in pdb can be obtained by typing ?
at the pdb prompt. Here's a link to the library documentation.
这篇关于在python / ipython中将函数变量转储到工作空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!