'Loading Message in Command Line

I want to create a "animated" Loading Message for the Command Line, where the dots increment by one until there are 4 dots and the it starts from the beginning. The Problem is, that is goes up to 4 dots and then only displays them the whole time. This is my Code:

def loading(self):
    global connected
    
    x = 1
    dots = '.'
    while not connected:
        while x <= 4:
            dots = dots + '.'
            print(f"\r[-] Waiting for Incoming Connections{dots}", end='\r')
            x += 1
            time.sleep(0.2)
        dots = '.'
        x = 1
    print(connected)

This Code should be run until a "Client" connects to an open Socket on the Server.

This is another Part of my Code:

class Server(cmd.Cmd):
intro = "Welcome"
prompt = f'{bcolors.OKBLUE}$SHELL >{bcolors.ENDC} '

def __init__(self) -> None:
    super(Server, self).__init__()
    self.HOST = ''
    self.PORT = 9011
    self.SOCKET = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.SOCKET.bind((self.HOST, self.PORT))
    self.logger = None
    self.wait_for_connection()
    
def wait_for_connection(self):
    global connected
    loading_bar = threading.Thread(target=self.loading, args=[])
    loading_bar.start()
        
    self.SOCKET.listen(1)
    conn, addr = self.SOCKET.accept()
    self.ACTIVE_SOCKET = conn
    connected = True

So in simple Terms:

  • Starting the Python Server part, then the "Loading" Should be displayed
  • When Client connects, then stop the "Loading" and display Shell Prompt

At the Moment with the specified Soulution the Loading is indeed stoped, but Prompt isnt displayed correctly



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source