简体   繁体   English

python 3.x从pickle恢复变量

[英]python 3.x restore variables from pickle

I have dozens of variables in a dictionary in a pickle. 我在泡菜词典中有几十个变量。 If certain conditions are true, I need to restore all of these variables (all different types), with the same names as the dict's keys. 如果满足某些条件,则需要还原所有这些变量(所有不同的类型),并使用与字典键相同的名称。

I simplified the code to point out the problem. 我简化了代码以指出问题。 For instance, one of the keys is 'ref10_data'. 例如,键之一是“ ref10_data”。 If the variable is defined elsewhere in the function, it doesn't get overwritten, but I would like it to be. 如果变量在函数中的其他位置定义,则不会被覆盖,但是我希望它会被覆盖。

import _pickle as pickle
from numpy import max

def main():
  processing_path = '/data/common/PROBSEV_DATA/processing/'
  ref10_data = 0
  restore_dict = pickle.load(open(processing_path + 'cc_rt_prob_svr.out','rb'))

  for key in restore_dict:
    globals()[key] = restore_dict[key]

  print(max(ref10_data))

if __name__ == '__main__':
  main()

'0' is what is printed. 打印的内容是“ 0”。 This question/answer kind of works, but it won't overwrite a variable if it is previously defined. 这种问题/答案的工作方式,但如果先前定义,则不会覆盖变量。 How do I get it to re-define a variable, or is there a better way to structure this functionality? 如何获得它以重新定义变量,还是有更好的方法来构造此功能? Thanks. 谢谢。

Instead of tampering with globals , which is inellegant and unpythonic, you can simply pass the variables as keyword arguments ("kwargs") to another function: 您可以简单地将变量作为关键字参数(“ kwargs”)传递给另一个函数,而不用篡改既笨拙又非蟒蛇的globals

def foo(ref10_data, another_var, yet_another_var):
    print(max(ref10_data))

def main():
    ...
    restore_dict = pickle.load(...)
    foo(**restore_dict)

This is simple, intuitive, and pythonic. 这是简单,直观和Pythonic的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM