我有两个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吗?

最佳答案

您可以从函数中返回它:

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 - 从不同的python模块访问变量的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19777959/

10-12 22:06