Как сделать что бы несколько функций работали одновременно python
Есть файл bot.py:
import xxx
class Bot:
def run(self):
client = xxx.Client()
client.login(email="email", password="password")
subclient = xxx.SubClient(comId="id", profile=client.profile)
oldMessages = []
with open("oldMessages.txt", "r") as oldFile:
for messageId in oldFile.read().split("\n")[:-1]:
oldMessages.append(messageId)
while True:
readChat = ["chatid"]
for chatId in readChat:
msg = subclient.get_chat_messages(chatId=chatId, size=10)
for message, messageId, author in zip(msg.content, msg.messageId, msg.author.nickname):
if not messageId in oldMessages:
print(chatId, author, message)
# "!ping" comnand
if str(message).startswith("!ping"):
subclient.send_message(chatId, "Pong!")
oldMessages.append(messageId)
with open("oldMessages.txt", "a") as oldFile:
oldFile.write(messageId + "\n")
oldFile.close()
def run2(self):
client = xxx.Client()
client.login(email="email", password="password")
subclient = xxx.SubClient(comId="id", profile=client.profile)
oldMessages = []
with open("oldMessages.txt", "r") as oldFile:
for messageId in oldFile.read().split("\n")[:-1]:
oldMessages.append(messageId)
while True:
readChat = ["chatid"]
for chatId in readChat:
msg = subclient.get_chat_messages(chatId=chatId, size=10)
for message, messageId, author in zip(msg.content, msg.messageId, msg.author.nickname):
if not messageId in oldMessages:
print(chatId, author, message)
# "!ping" comnand
if str(message).startswith("!ping"):
subclient.send_message(chatId, "Pong!")
oldMessages.append(messageId)
with open("oldMessages.txt", "a") as oldFile:
oldFile.write(messageId + "\n")
oldFile.close()
И файл main.py:
from lib.bot import Bot
# Initialize the bot
bot = Bot()
if __name__ == '__main__':
print("START")
bot.run()
bot.run2()
Как можно сделать так, что бы функции run и run2 работали одновременно?
Ответы (1 шт):
Автор решения: V-Mor
→ Ссылка
Вот ответ с использованием модуля threading:
from lib.bot import Bot
from threading import Thread
# Initialize the bot
bot = Bot()
if __name__ == '__main__':
print("START")
# Создаём два потока для каждого из методов
t1 = Thread(target=bot.run)
t2 = Thread(target=bot.run2)
t1.start() # Запустили один метод на выполнение в потоке
t2.start() # Не дожидаясь окончания первого, запустили второй на выполнение в другом потоке
t1.join() # Теперь ждём завершения первого (второй при этом тоже выполняется)
t2.join() # Ждём завершения второго (если второй завершится раньше первого, ожидания просто не будет)
P.S. Вот, вроде бы, неплохая статья про многопоточность в целом и в Python в частности.