How to kill a process created by subprocess by ano

2020-05-02 13:11发布

问题:

I'm wondering why I can't terminate a batch file raised from one function by using another function.

What I'm trying to do is to manage the batch file on my dedicated computer by Telebot.

My test.bat file:

title test.bat
timeout /t 999

I've written a separated module with functions to start and kill this batch file:

from os import path, kill
import subprocess
import signal


TEST_PATH = 'C:\\Users\\Administrator\\Desktop\\TEST\\'
un_proc = None 


class sidim(object):
    def __init__(self):
        pass

    def launch_test(self):
        test_proc = subprocess.Popen([path.join(TEST_PATH,
                                                'TEST.bat')],                                                                              
                          creationflags=subprocess.CREATE_NEW_CONSOLE)
        self.test_pid = test_proc.pid

    def kill_test(self):
        kill(self.test_pid, signal.SIGTERM)

And when I'm starting the batch file using the /start_test command it works fine and the batch file is launching properly:

import telebot 
import sidimanager

bot = telebot.TeleBot('TOKEN')
sidim = sidimanager.sidim()


@bot.message_handler(commands=['start_test'])
def handle_start_test(message):
    sidim.launch_test()
    bot.reply_to(message, 'Test .bat file has been successfuly launched.')

But when I'm trying to terminate this batch with the /kill_test command the batch file ignores that and continues to work:

@bot.message_handler(commands='kill_test')
def handle_kill_test(message):
    sidim.kill_test()
    bot.reply_to(message, 'Test .bat file has been successfuly killed.')

How can I kill it?

回答1:

I am calling the batch through a new cmd.exe process. In some cases, it feels that the commands in the batch are running in the 'background':

import subprocess

test_proc = subprocess.Popen(['cmd',  '/c',  'C:/temp/myBatch.bat'], creationflags=subprocess.CREATE_NEW_CONSOLE)
test_pid = test_proc.pid

Now you are having the batch running isolated in a new CMD process, that can be easily killed using taskkill /F /PID 1234 via Popen.

Note: You might need to provide full paths to cmd.exe, taskkill.exe and your batch, depending on how your 'main script' is started.