Good day. I have two processes, one of them is a client, the other is a server. It is necessary for me that they together in one file. As a result, in the log file I should get something like this:

bot1>sending message: hi! bot2>got message: hi! bot2>sending answer: hello you too bot1>got message: hello you too bot1>sending message: green bot2>got message: green bot2>sending answer: bonjourna bot1>got message: bonjourna bot1>got wrong message, expected: apple, received: bonjourna bot1>sending message: green bot2>got message: green bot2>sending answer: bonjourna bot1>got message: bonjourna bot1>got wrong message, expected: apple, received: bonjourna 

I decided to use the following algorithm:

1. The server opens the file, writes its log there, then closes the file.

2. The client opens the file, writes his log there, then closes the file.

3. The server opens the file, writes its own log there, then closes the file.

.... And so they do to the bitter end.

Please tell me how to implement such an algorithm?

  • 3
    make a separate server for logging and let it write to the file. and the client and server send him what to write to the file. - Mikhail Vaysman

1 answer 1

 import threading def log_write(text: str, file='log.txt', lock=threading.Lock()): lock.acquire() # закрывает lock try: with open(file, 'a') as f: # открывает файл f.write(text) # записывает туда свой лог finally: # затем закрывает файл lock.release() # затем открывает lock class B(threading.Thread): def run(self): # логгировались вдвоем в один файл [log_write('{}>{}\n'.format(self.name, a)) for a in range(20)] B().start() # У меня есть два процесса B().start() # У меня есть два процесса