在Python中跨模块共享全局变量
我有两个模块。我想使用全局变量在Python中跨模块共享全局变量,python,global-variables,Python,Global Variables,我有两个模块。我想使用全局变量server将响应发送到服务器。当我尝试发送数据时,它会显示管道破裂,这意味着连接已断开。因此,数据无法发送。它所做的是,在将tcp\u驱动程序导入send\u response文件时,它再次初始化服务器变量,由于变量保持未连接,因此返回断管错误 如何使用全局变量server发送数据 PS:我不想将服务器变量作为参数传递。我也不想将服务器变量保存到第三个模块中,从而从第三个模块继承它 以下是我的模块 tcp\u驱动程序.py import send_response
server
将响应发送到服务器。当我尝试发送数据时,它会显示管道破裂,这意味着连接已断开。因此,数据无法发送。它所做的是,在将tcp\u驱动程序
导入send\u response
文件时,它再次初始化服务器
变量,由于变量保持未连接,因此返回断管错误
如何使用全局变量server
发送数据
PS:我不想将服务器变量作为参数传递。我也不想将服务器变量保存到第三个模块中,从而从第三个模块继承它
以下是我的模块
tcp\u驱动程序.py
import send_response
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR, 1)
server_address = (config.IP_ADD, config.PORT)
def main():
while True:
try :
server.connect(server_address)
print "Connected"
break
except socket.error: # Tries to connect to the server until it is connected.
print "Not Connected"
continue
response = "Hello Server"
send_response.send_response_to_server(response)
if __name__ == "__main__":
main()
import tcp_driver
def send_response_to_server(response):
try : server.send(response)
except : tcp_driver.main() # if connection is broken, it tries to connect again.
send_response.py
import send_response
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR, 1)
server_address = (config.IP_ADD, config.PORT)
def main():
while True:
try :
server.connect(server_address)
print "Connected"
break
except socket.error: # Tries to connect to the server until it is connected.
print "Not Connected"
continue
response = "Hello Server"
send_response.send_response_to_server(response)
if __name__ == "__main__":
main()
import tcp_driver
def send_response_to_server(response):
try : server.send(response)
except : tcp_driver.main() # if connection is broken, it tries to connect again.
因为它只是我的大型代码的一个样本,已经模块化了。因此,请相应地响应。此外,如果我将
发送\u响应\u到\u服务器
到tcp\u驱动程序
文件,并从另一个模块调用发送\u响应\u到\u服务器
,仍将导致相同的错误。