从不同的python模块访问变量的最佳方法是什么?

时间:2013-11-04 21:56:01

标签: python python-2.7

我有两个python脚本,一个用于处理数据,另一个用于创建反映已处理数据的HTML报告。

test1.py:

def test(self):
    for i in data:
        if data is this:
            data[1] = something
        if data is that:
            data[1] = something
        else:
            data[1] = something else

test2.py:

OutFile = open("C:/path/../result.html", "w")

print "Content-type:text/html\r\n\r\"
# want to print data[1] value here

data[1]中的值从test1.py传递到test2.py的最佳方式是什么?我可以使用参数传递给test2.py吗?

2 个答案:

答案 0 :(得分:3)

你可以从函数中返回它:

class MyClass():
    data = some_data
    def test(self):
        for i in data:
            if data is this:
                data[1] = something
            if data is that:
                data[1] = something
            else:
                data[1] = something else
            return data

test2.py中,抓住并把它放在某处:

from test1 import MyClass
my_instance = MyClass()
data = my_instance.test()
print(data[1])

备选方案1

将其作为MyClass中的变量:

class MyClass():
    data = some_data
    def test(self):
        for i in self.data:
            if self.data is this:
                self.data[1] = something
            if data is that:
                self.data[1] = something
            else:
                self.data[1] = something else

test2.py中,将其视为my_instance的属性:

from test1 import MyClass
my_instance = MyClass()
my_instance.test()
print(my_instance.data[1])

备选方案2

如果您想独立运行这两个脚本,可以test1将数据放在test2可访问的位置。例如,在文件中:

class MyClass():
        data = some_data
        def test(self):
            for i in data:
                if data is this:
                    data[1] = something
                if data is that:
                    data[1] = something
                else:
                    data[1] = something else
            with open('data.txt', 'w') as f:
                f.writelines(data)

现在,您可以轻松地从第二个脚本中获取它:

with open('data.txt') as f:
    data = f.readlines()
print (data[1])

实现这一点并不困难。

希望这有帮助!

答案 1 :(得分:0)

一种选择是使用python pickle包:

import pickle
#in py1
pickle.dump(data, open(some_dir + "data.pkl","wb"))
#in py2
data = pickle.load(open(some_dir + "data.pkl","rb"))

虽然我不确定你的名单有多大;这对于大型列表来说会很慢。如果它只是几个值,则开销将不存在。

相关问题