'python import socket class from other modules
I have created a class(object) connection_manager using socket TCP in a module (connection.py):
#file connection.py
HOST = "127.0.0.1" # Standard loopback interface address (localhost)
PORT = 8001 # Port to listen on TCP/IP
PORT1 = 8002 # Port to listen on UDP/IP
class connection_manager(object):
def creat_tcp_connection(self):
try:
self.client_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_server_address = (HOST, PORT)
except:
print("Serveur TCP Introuvable")
finally:
print('Connecting to TCP server:' + str(tcp_server_address))
self.client_tcp.connect(tcp_server_address)
print('Connection TCP sucessful')
return self.client_tcp
Now I want to import this class into test.py to use this socket. So I did:
#file test
import socket
import sys
import connection as cnx
def test_function():
try:
texte = "ABC\n"
cnx.client_tcp.send(texte.encode())
data=cnx.client_tcp.recv(1024)
except:
print("error occur")
finally:
print('closing test')
if __name__ == "__main__":
p1 = cnx.connection_manager()
test_function()
But It got the error:
AttributeError: 'connection_manager' object has no attribute 'client_tcp'
In the same module, in test_function I can use:
self.client_tcp.send(texte.encode())
data=self.client_tcp.recv(1024).decode('utf-8')
s But in different modules, I don't know how to do it? How can I import the class using socket from this module into another module? Many thanks
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|