M
M
Maxim2016-09-29 15:53:24
Python
Maxim, 2016-09-29 15:53:24

How to kill streams that I myself created?

Hello.
The thing is.
There is a telegram bot.
When sending a command to the bot, for example, /check 192.168.0.1, it creates a thread with the name "sender id + address" (in our example, the address will be 192.168.0.1).
In this thread, a loop is endlessly executed in which the address is pinged and the results are sent back to the one who created this thread.
After some time, some of the threads need to be nailed, and some should be left.
Accordingly, I send a command for example / kill 192.168.0.1
and how can I now kill a thread with the name "sender id + address"
how to get all active threads, I understand:

for i in range(threading.active_count()):
               print(threading.enumerate()[i])

and here's what I haven't figured out yet.
Help a noob.
Example.
a working bot named TosterQuest_bot
needs to be done pip install pyTelegramBotAPI
import threading, random, time, telebot

bot = telebot.TeleBot('276349923:AAGq2JkAib-OwGo-SrW1lHbh4CTPVFmY0ns')


@bot.message_handler(commands=['cr'])
def handle_text(message):
        param = str(random.randint(1, 1000))
        threadname = str(message.from_user.id) + " " + param
        th = threading.Thread(target=inffync, name=threadname, args=[param])
        th.start()


@bot.message_handler(commands=['list'])
def handle_text(message):
    for i in range(threading.active_count()):
        print(threading.enumerate()[i])


@bot.message_handler(commands=['kill'])
def handle_text(message):
    print("Хочу убивать потоки созданные " + str(message.from_user.id))


def inffync(p):
    while True:
        print(str(random.randint(1, 1000)) + "   " + p)
        time.sleep(5)
bot.polling(none_stop=True, interval=0)

if you send him the /cr command, he will create a thread in which the function that displays a random number will be endlessly executed.
if you send /list, a list of running threads will appear in the console.
now how to arrange the murder of one of them with the /kill command?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nirvimel, 2016-09-29
@Grol

The loop checks for a flag (exit condition) initially set to False but reset to True by the /kill command handler. It is convenient to use dict to assign exit flags to individual threads.

O
Oleg Tsilyurik, 2016-09-29
@Olej

Accordingly, I send the command

At your command (although I did not understand to whom and how you give the command?) you need to exit the loop in the thread and return the thread function.
Search here:
Python - Parallelism
The subtleties of using the Python language: Part 4. A couple ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question