Python 尝试除了不使用导入变量

Python try except not using imported variable

导入模块,connection_status_message.py:

connection_status_message = "Not Connected"

尝试排除文件,connect_to_server.py:

from Server.connection_status_message import connection_status_message

def connect_to_server(host,user,password):
    try:
        connect(host,user,password)
    except NoConnection:
        connection_status_message = "Could not reach host..."
        return
...

问题是变量正试图成为本地变量。所以我阅读了这个问题并了解了如何引用全局变量:

def connect_to_server(host,user,password):
    try:
        connect(host,user,password)
    except NoConnection:
        global connection_status_message
        connection_status_message = "Could not reach host..."
        return
...

但现在 PyCharm 声明不再使用顶部的导入语句。

如何让这个 Try/Except 使用导入的变量?

我无法复制你的问题,但如果你的 import 行存储在一个函数下,变量是 nonlocal instead of global:

def connect_to_server(host,user,password):
    try:
        connect(host,user,password)
    except NoConnection:
        nonlocal connection_status_message
        connection_status_message = "Could not reach host..."

另一种方法是不将变量直接加载到您的命名空间中,这样您就可以参考它的来源以避免创建局部变量:

from Server import connection_status_message as csm
csm.connection_status_message

# "No Connection"

def func():    
    csm.connection_status_message = "Could not reach host..."

csm.connection_status_message

# "Could not reach host..."

您也可以考虑创建一个 class 来将所有这些作为一个对象来处理:

class Connection(object):
    def __init__(self):
        self.connection_status_message = "No Connection"
        # TODO: initialize your class

    def connect(self, host, user, password):
        # TODO code connect criteria stuff here

    def connect_to_server(self, host, user, password):
        try:
            self.connect(host,user,password)
        except NoConnection:
            self.connection_status_message = "Could not reach host..."
            # ... return whatever ...#

现在您可以 from Server import Connection 并创建一个本地 Connection 对象来操作:

conn = Connection()
conn.connect_to_server(host, user, password)

这可能是显而易见的,但在任何情况下,该值仅在此执行期间存储在内存中。实际的 connection_status_message.py 永远不会用这个值更新。