导入的模块,connection_status_message.py:
connection_status_message = "Not Connected"
尝试使用Except文件,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正在声明顶部的import语句已不再使用。
如何使用此Try / Except来使用导入的变量?
答案 0 :(得分:1)
我无法复制您的问题,但如果您的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 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
永远不会使用此值进行更新。