繁体   English   中英

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

[英]What is best way to access variables from different python modules?

我有两个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.pytest2.py的最佳方法是什么? 我可以使用参数传递给test2.py吗?

你可以从函数中返回它:

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

实现这一点并不困难。

希望这可以帮助!

一种选择是使用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"))

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

暂无
暂无

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

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