user7432329
user7432329

Reputation: 33

Global Variable in Python cross module

I have two Python modules:

I want to change X global variable in two.py.Script two.py running. After I run one.py

one.py

#!/usr/bin/env python

import two

def main():
 two.function("20")

if __name__=="__main__":
    main()

two.py

#!/usr/bin/env python

X="10"
def main():
 while True:
  function()
 time.sleep(0.25)

def function(input="00"):
 if(input!="00"):
      global X
      X=input
      print "change"

 print X
if __name__=="__main__":
  main()

console:

sudo python two.py

10
10
10
10

after I run one.py  but no change in two.py

Upvotes: 2

Views: 242

Answers (1)

Mathieu Paturel
Mathieu Paturel

Reputation: 4510

after I run one.py but no change in two.py

What you're doing dynamically changes the variables. It doesn't re-write the files.

Which is in fact, what you might want to do.

myfile.txt

5

reader.py

with open('myfile.txt', 'r') as fp:
    nb = int(fp.read())
    print(nb)

writer.py

with open('myfile.txt', 'w') as fp:
    fp.write('6')

Now, if you run reader.py, it'll output 5. Then if you run writer.py, it'll output nothing, just replace the entire content of myfile.txt with 6. And then, rerun reader.py, it'll output 6, because the content of the file as changed. It works because, unlike your program that you run, the files' content doesn't depend of a process, it's "static".

Upvotes: 1

Related Questions