Python:如何在调试时保存当前变量?

10

我在python中有一个一般性的调试问题(如果有必要,在pycharm IDE中)

假设我有两个代码块:

Code block 1 (takes very long to run)
Code block 2 (where I want to debug)

在运行代码块1后,是否有一种方法可以保存当前变量,以便我可以“倒回”到那些变量的状态并从那里进行调试,而不必重新运行整个脚本来重新计算这些变量?

3个回答

2

我不知道有一个通用的解决方案来解决这个问题。但是可以使用各种序列化对象的方法构建应用程序特定的解决方案,但我建议在这个问题上使用pickle

就像其他许多东西一样,在SO上已经有一个小例子。


2
您可以在运行代码块1结束时“保存”当前变量。只需将变量存储在字典中,并在第一个代码块完成后将其写入文件即可。
这里是一个非常简单的示例,因为您没有提供任何数据:
import csv

# code block 1
for i in range(1000000): # meant to simulate a "long" time
    var1 = 2*i
    var2 = 4*i

# basically this is a log that keeps track of the values of these variables
to_save = {'var1': var1, 'var2': var2}

# write that dictionary to a file
with open('my_log.csv', 'w+') as f:
    w = csv.DictWriter(f, to_save.keys())
    w.writeheader()
    w.writerow(to_save)

# continue with code block 2
for i in range(1000):
    var1 = "BLAH"
    var2 = "BLAH BLAH"

0
我只想在 pickle 响应中添加一些内容。
我的一般方法也包括了 pickle,但结合了 pytest 和 pytest fixtures。
我将想要调试的代码包装在一个测试中,并模拟耗费时间的操作以返回预先 pickle 的值。
举例说明:
@pytest.fixture
def data():
    return pickle.load(...)
    

def test(data):
    with mock.patch("heavy_func") as mocked:
        mocked.return_value = data

        # my_func makes a call to `heavy_func` but at that moment
        # `heavy_func` will be a mock object and will return `data`
        # no matter the params you provide to it.
        # Usefully also to get rid of HTTP and DB calls when 
        # testing.
        result = my_func() 

然后我调试测试


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接