简体   繁体   English

Python跨模块中的全局变量

[英]Global Variable in Python cross module

I have two Python modules:我有两个 Python 模块:

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

I want to change X global variable in two.py .Script two.py running.我想在运行的two.py .Script two.py更改X全局变量。 After I run one.py在我运行one.py

one.py一个.py

#!/usr/bin/env python

import two

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

if __name__=="__main__":
    main()

two.py两个.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

after I run one.py but no change in two.py在我运行 one.py 但在 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 .现在,如果您运行reader.py ,它将输出5 Then if you run writer.py , it'll output nothing, just replace the entire content of myfile.txt with 6 .然后,如果您运行writer.py ,它不会输出任何内容,只需将myfile.txt的全部内容替换为6 And then, rerun reader.py , it'll output 6 , because the content of the file as changed.然后,重新运行reader.py ,它将输出6 ,因为文件的内容已更改。 It works because, unlike your program that you run, the files' content doesn't depend of a process, it's "static".它之所以有效,是因为与您运行的程序不同,文件的内容不依赖于进程,它是“静态的”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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