2

I have two Python modules:

  • one.py; and
  • two.py

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
3
  • 3
    Why do you run two.py with sudo? Commented Jan 17, 2017 at 21:14
  • 2
    Well you'll be running two.py as a separate Python process than one.py so you can't really change global variables like that. You'll need some kind of inter-process communication. Commented Jan 17, 2017 at 21:41
  • Hi Tagc inter-process communication is Thread ? Commented Jan 25, 2017 at 22:11

1 Answer 1

1

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".

Sign up to request clarification or add additional context in comments.

1 Comment

It is Solutions Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.