How can I mutually share variables between two python scripts?

I have two scripts, first.py and second.py. I want to send variables from first to second and variables from second to first. But this shows an error. Can anyone help me?

first.py

import second

a=10

print second.b

      

second.py

import first

b=15

print first.a

      

Mistake

AttributeError: 'module' object has no attribute 'b'

+3


source to share


3 answers


Quite frankly, you don't want to do this. This can lead to cyclical imports (or partial imports) and a lot of confusion. What you usually want is a main program that will import the other two. The main program can then transfer data from one to the other, since it has access to both.

There is also a post / subscribe idea - https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern



In Python you can do it yourself or you can use a handy package like PyPubSub or PyDispatcher

+4


source


You can use a simple memcached server for this. https://pypi.python.org/pypi/python-memcached



0


source


Alternatively, if this is also something that someone might find useful, you can try writing it to a third file (call it variable.txt or whatever)

0


source







All Articles