Python: How to save current variables while debugging?

后端 未结 2 912
说谎
说谎 2021-01-18 01:49

I have a general debugging question in python (pycharm IDE if it matters)

Lets say I have code which is made up of 2 blocks:

Code block 1 (takes very         


        
相关标签:
2条回答
  • 2021-01-18 02:41

    You can certainly "save" the current variables at the end of running code block 1. Just store the variables in a dictionary and write that to a file after the first code block finishes.

    Here's a very minimal example, since you provided no data:

    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 讨论(0)
  • 2021-01-18 02:53

    I am unaware of a general solution to this problem. But an application specific solution can be constructed using various methods for serializing objects, but I would suggest pickle for this problem.

    Like so much else, there is a small example already on SO.

    0 讨论(0)
提交回复
热议问题