Skip to main content
 首页 » 编程设计

python之访问脚本主模块内定义的python类变量

2025年05月04日6thcjp

我有一个使用 celery 进行异步任务处理的 django 项目。我正在使用 python 2.7。

我的 django 项目中的模块 client.py 中有一个类:

# client.py 
class Client: 
    def __init__(self): 
        # code for opening a persistent connection and saving the connection client in a class variable 
        ... 
        self.client = <connection client> 
 
    def get_connection_client(self): 
        return self.client 
 
    def send_message(self, message): 
        # --- Not the exact code but this is the function I need to access to for which I need access to the client variable--- 
        self.client.send(message) 
    # Other functions that use the above method to send messages 
    ... 

此类只需实例化一次即可创建到远程服务器的持久连接。

我运行了一个无限期运行的脚本 connection.py:

# connection.py 
from client import Client 
if __name__ == '__main__': 
    clientobj = Client() 
    client = clientobj.get_connection_client() 
    # Blocking process 
    while True: 
        # waits for a message from the remote server 
        ... 

我需要从另一个模块 tasks.py 访问变量 client(celery 需要)。


# tasks.py 
... 
from client import Client 
@app.task 
def function(): 
    # Need access to the client variable 
    # <??? How do I get an access to the client variable for the  
    # already established connection???> 
    message = "Message to send to the server using the established connection" 
    client.send_message(message) 

所有三个 python 模块都在同一台机器上。 connection.py 作为独立脚本执行并首先执行。 tasks.py 中的方法 function() 在需要时会在项目的其他模块中多次调用,因此,我无法实例化 Client 这个方法里面的类。全局变量不起作用。


在java中,我们可以创建全局静态变量并在整个项目中访问它。我们如何在 Python 中执行此操作?

我能想到但不确定是否可以在 python 中完成的方法:

  • 将这个变量保存在一个公共(public)文件中,以便它可以在我项目的其他模块中访问?
  • 将此客户端保存为 django 或 celery 中的设置并在所需模块中访问此设置?
  • 根据 sebastian 的建议,另一种方法是在运行的进程之间共享变量。我基本上想这样做。我如何在 Python 中执行此操作?

对于那些有兴趣知道为什么需要这样做的人,请see this question .它解释了完整的系统设计和涉及的各种组件。

我愿意接受需要更改代码结构的建议。

请您参考如下方法:

multiprocessing提供了执行此操作所需的所有工具。

connection.py

from multiprocessing.managers import BaseManager 
from client import Client() 
client = Client() 
class ClientManager(BaseManager): pass 
ClientManager.register('get_client', callable=lambda: client) 
manager = ClientManager(address=('', 50000), authkey='abracadabra') 
server = manager.get_server() 
server.serve_forever() 

tasks.py

from multiprocessing.managers import BaseManager 
class ClientManager(BaseManager): pass 
ClientManager.register('get_client') 
manager = ClientManager(address=('localhost', 50000), authkey='abracadabra') 
manager.connect() 
client = manager.get_client() 
 
@app.task 
def function(): 
    message = "Message to send to the server using the established connection" 
    client.send_message(message)