Search code examples
pythonprocesskillabort

Ending external programs with Python


I'm writing a program that needs to be able to kill certain processes. The two lines I'm currently using work; however, the second line os.system(task) launches command prompt for a split second whilst it's ending a process. Are there any equivalent lines which do not launch command prompt?

Snippet :

task = 'taskkill /im ' + taskname + ' /f'
os.system(task)

This is in Windows 7 if you couldn't have guessed.


Solution

  • Try using subprocess.check_call instead of os.system. This won't launch the process in a console window.

    import subprocess
    taskname = '...'
    task = 'taskkill /im ' + taskname + ' /f'
    subprocess.check_call(task, shell=True)