我在python中有一个一般性的调试问题(如果有必要,在pycharm IDE中)
假设我有两个代码块:
Code block 1 (takes very long to run)
Code block 2 (where I want to debug)
在运行代码块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"
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()
然后我调试测试