简体   繁体   English

从Python中的外部文件将变量导入函数

[英]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. 只在本地导入变量,而我不能在每个函数中使用import,因为Python告诉我在模块级别不允许这样做。 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 . 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? 将所有要保存的参数附加到一个对象,然后使用pickle模块来处理序列化会不会更容易?

>>> 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
>>>

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

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