0

For context I am making a game, in the game there is a multiplayer feature, when I click on the multiplayer button is works as it imports a file client.py, after the first game ends, I need to call client.py once again as there a line client.connect(ADDR) in the global scope. But python refuses to import the file again, I need the client to connect again as it disconnects after the first game.... Any ideas?

client.py:

import socket
print("HIII") #This is was there for testing

HEADER = 6400
PORT = 5050
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
SERVER = "<Ipv4 address here>"
ADDR = (SERVER, PORT)

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)

def send(msg, send=True):
    if send:
        message = msg.encode(FORMAT)
        client.send(message)

    msgFromServer = client.recv(HEADER).decode(FORMAT)
    return msgFromServer
BoomTNT29
  • 3
  • 2

1 Answers1

2

I think you can try to make it a function, like

import socket
def run_client():
    print("HIII")
    HEADER = 6400
    ...

and from client import run_client in the main file. In this way, you can import the function once and use it whenever you want to use it.

Sirius Koan
  • 51
  • 2
  • 4
  • Yee it worked, but is there a more efficient way to do it? – BoomTNT29 Aug 15 '21 at 07:39
  • If you really want to "reimport" it, you can try the [snippet](https://pastebin.com/ARQy1GrK). The solution is from [this question](https://stackoverflow.com/questions/1254370/reimport-a-module-in-python-while-interactive), so you can check it out. – Sirius Koan Aug 15 '21 at 07:57
  • If you still want that the function will run first when you import the file, call the function in the global scope in the file – user107511 Aug 15 '21 at 08:12
  • @SiriusKoan I think that is what I wanted to do thank you – BoomTNT29 Aug 15 '21 at 08:19