'How to end or kill a socket process on android? (Edited) how can i say yes with python to an os.system()?

I have this function on a thread running with kivy when i close the app i have to close this socket manually so i can re-run it i tried to socket.SO_REUSEADDR, 1 but it did'nt work and i have this after at end of the code chat_recv_socket.close(). What i want is a more efficient way to kill or end this socket at the except block.

def func_chat_recv_socket():
    global chat_recv_string, myip, chat_recv_socket
    while True:
        if myip != '':
            break
    while True:
        try:
            chat_recv_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            chat_recv_socket.bind((myip, 4600))
            chat_recv_socket.listen(10)
            while True:
                clientsocket, address = chat_recv_socket.accept()

                while True:
                    chat_recv = clientsocket.recv(100)
                    print('recieving msg')
                    chat_recv_string = chat_recv.decode("utf-8")
                    print(chat_recv)
                    clientsocket.close()
                    break           
        except:
            ### sys or os workaround on android
            time.sleep(0.5)
            print('binding')

This part was add after

After using this

os.system('freeport 4600')

I am getting this :

Process Type: 'python3'  Port: 4600. Kill?[yes/no]

How can u say say from python? this solution wont work because this command needs to be executed width the sudo. here is the output:

sudo: a terminal is required to read the password; either use the -S option to read from standard input or configure an askpass helper
No process running on port 4600 by current user. Checking if root is running the proecess
No process found running on port 4600.


Solution 1:[1]

the app has a different behavior on Android, with the catlog from adb android it seems that after closing and opening the app the socket is closed with it, on reopening no error is printed and the socket gets binded as expected. its not a solution but its enough for me right now.

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Oussama