我在python中有一个常见的调试问题(pycharm IDE,如果重要的话)
假设我的代码由2个块组成:
Code block 1 (takes very long to run)
Code block 2 (where I want to debug)
有没有办法在运行代码块1结束时保存当前变量,这样我就可以倒回"从那里回到那些变量状态和调试,而没有重新运行整个脚本来重新计算这些变量?
答案 0 :(得分: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"
答案 1 :(得分:2)