简体   繁体   中英

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

I have two python scripts, one which processes data and other which creates an HTML report reflecting the processed data.

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

What is the best way to pass the value in data[1] from test1.py to test2.py ? Can I pass using arguments to test2.py ?

You can just return it from the function:

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

And in test2.py , grab and put it somewhere:

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

Alternative 1

Put it as a variable in 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

And in the test2.py , take it as a property of my_instance :

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

Alternative 2

If you want to run both scripts independently, you can make test1 put the data somewhere accessible by test2 . For example, in a file:

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)

Now, you can easily have it from your second script:

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

It's not that difficult to achieve this.

Hope this helps!

One option would be to use the python pickle package:

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

Although I am not sure how big your lists are; this will be slow for huge lists. If its just a few values though, the overhead will be nonexistent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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