Python交叉模块中的全局变量

时间:2022-03-23 05:09:36

I have two Python modules:

我有两个Python模块:

  • one.py; and
  • one.py;和
  • two.py
  • two.py

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

我想把X全局变量换成2。py。两个脚本。py运行。之后我跑one.py

one.py

one.py

#!/usr/bin/env python

import two

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

if __name__=="__main__":
    main()

two.py

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

1 个解决方案

#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

myfile.txt

5

reader.py

reader.py

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

writer.py

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

现在,如果你运行阅读器。py,它会输出5。如果你运行writer。py,它不会输出任何内容,只是替换myfile的整个内容。txt和6。然后,重新运行读者。py,它将输出6,因为文件的内容已经更改。它之所以有效,是因为与您运行的程序不同,文件的内容不依赖于进程,它是“静态的”。

#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

myfile.txt

5

reader.py

reader.py

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

writer.py

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

现在,如果你运行阅读器。py,它会输出5。如果你运行writer。py,它不会输出任何内容,只是替换myfile的整个内容。txt和6。然后,重新运行读者。py,它将输出6,因为文件的内容已经更改。它之所以有效,是因为与您运行的程序不同,文件的内容不依赖于进程,它是“静态的”。