修改不同模块中的变量

时间:2014-06-19 21:17:15

标签: python python-2.7

我是python和编程的新手,所以这可能很容易,但我无法在任何地方找到合适的答案。我试图做以下事情。我想在模块中有一个模块,其中有一些变量应由我的主模块修改。 另外,从一开始就不清楚具有变量和变量的模块是否已经存在。 目前我正在做以下事情:

# test2.py
import os

# creates module test1
if os.path.isfile('test1.py') and os.path.getsize('test1.py') > 8:
    pass
else:
    txt = open('test1.py','w')
    txt.write('testvar = {}')
    txt.close()

import test1
testvar = test1.testvar

我的testmodule看起来如下:

# test.py
import test2

testvar = test2.testvar
# now modify testvar

txt = open('test1.py','w')
txt.write('testvar = '+repr(testvar))
txt.close()

这有效,如果在python中运行test.py但它有缺点,我需要一个单独的模块用于任何类似testvar的变量。如果我可以使用包含许多此类变量的单个模块并使用某种test1.testvar.update(entry) - 方法来更改变量,我更愿意。 此外,如果我使用py2exe创建一个exe文件,应用程序不会识别testvar-variable。所以这种方法还有一个问题。 我想要这一切的原因是在程序的许多不同运行期间更改变量。 感谢您的任何建议。

1 个答案:

答案 0 :(得分:1)

您正在尝试使用Python动态创建新的Python代码,然后将其加载到原始程序并执行......?

这是许多重大和轻微灾难的食谱。不要这样做。

如果您需要以持久的方式存储数据,从一个程序运行到另一个程序,有很多好方法可以做到这一点。 Python的标准shelve module是一种非常简单的方法。你基本上只是打开一个文件并立即开始使用它,就像一个dict对象,可以存储(几乎)其他任何东西。

import shelve

sh = shelve.open("myshelf")

sh["foo"] = (1,2,3,4)
sh["bar"] = "I like spam"

sh.close()

sh = shelve.open("myshelf")
print sh["foo"]
print sh.keys()

更新:如果您需要人类可读的输出文件,请尝试使用广泛使用的JSON serialization format

  • shelf不同,json模块要求您显式保存和恢复字典对象。
  • 如果没有额外的代码,JSON格式无法序列化与shelf一样多的数据类型。例如,它可以序列化dict / list,但无法序列化set并将tuple更改为list

使用JSON也是如此。请注意,元组sh["foo"]在序列化和反序列化时作为列表返回:

import json

# Load sh from JSON file or create a new dictionary if it doesn't exist
try:
    sh = json.load( open("storage.json","r") )
except IOError:
    sh = {}

sh["foo"] = (1,2,3,4)
sh["bar"] = "I like spam"

# Save sh to JSON file
json.dump( sh, open("storage.json","w") );

# Reload it
sh = json.load( open("storage.json","r") )

print sh["foo"]
print sh.keys()
相关问题