简体   繁体   中英

Import variables into functions from external file in Python

I am trying to write a script that is rather long, uses several different data sources and can go wrong at many different stages. Having to restart the whole process from the beginning each time some error in the input data is discovered is not too much fun so I though I would save variables (actually paths to created data files) to a backup file then read in this file and pick up where I left off. Unfortunately

from previousrun import *

only imports the variables locally and I can't use import in each function as Python tells me its not allowed at module level. Is there any way of importing an unknown number of variables from another file and have them globally available?

Use this in your function:

`locals().update(importlib.import_module("importlib").__dict__)`

and import importlib .

Wouldn't it be easier to just attach all the parameters you want to save to an object and then use the pickle module to handle serialization?

>>> class Save(object): pass
...
>>> s = Save()
>>> s.foo = 'foo'
>>> s.bar = 42
>>> import pickle
>>> fp = open('save.pickle', 'wb')
>>> pickle.dump(s, fp)
>>> fp.close()
>>>
>>> fp2 = open('save.pickle', 'rb')
>>> s2 = pickle.load(fp2)
>>> s2.foo
'foo'
>>> s2.bar
42
>>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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