Python 多个文件中的全局变量

Python Global Variables in multiple files

我有 2 个守护进程,它们应该访问同一个变量。 我为全局变量创建了第三个文件,每个守护进程都可以访问该变量。但是当一个改变变量时,另一个仍然看到默认值。

示例:

glob.py

time = 0

守护进程一个:

import datetime
import time
import glob

while(True):
    glob.time = datetime.datetime.now()
    time.sleep(30)

守护进程 b:

import glob

while(True):
    print(glob.time)

每次都会打印0 我希望我已经把我的问题说清楚了,有人可以帮助我。 如果您需要更多信息,请随时询问。

看起来(尽管您没有明确说明)您是 运行 您的程序,完全独立:Python 解释器的两次不同调用。

并没有你希望的那样神奇:就像你有同一个程序的两个实例一样运行,每个实例都有它的变量实例(全局或其他)。

如果你正在执行一些简单的任务,更简单的方法是让一个文本文件作为每个进程的输出,而另一个进程试图从它想知道的每个进程生成的文件中读取信息-(您甚至可以在 Unix 中使用命名管道)。

另一种方法是使用 multiprocessing stdlib 模块使用 Python 脚本来协调守护进程的启动,然后创建一个 multiprocessing.Manager 对象以直接在它们之间共享变量过程。 起初设置起来可能会更复杂,但这样做很干净。在此处查看 Manager class 上的文档: https://docs.python.org/3/library/multiprocessing.html

How do I share global variables across modules?

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere.:

import time
import glb

while(True):
    glb.t +=  1
    time.sleep(3)
    print glb.t 

b.py:

import glb
import a
while(True):
    print(glb.t)

glb.py:

t = 0

启动后输出a.py:

python b.py
1
2
3
4
5
6