使用Python结束任务时出现问题

时间:2014-06-25 10:50:20

标签: python windows-8 cmd

我知道在windows cmd中我可以输入以下文字来结束一个过程:

taskkill/im chrome.exe /f

但我怎么能用Python做呢?

我试过这个:

from subprocess import *
call("taskkill/im chrome.exe /f", shell=True)

但它表明了这一点:

'taskkill' is not recognized as an internal or external command, operable program or batch file.

那么我的代码有什么问题?我怎样才能使它发挥作用?

3 个答案:

答案 0 :(得分:0)

试试这个:

import os

os.system("taskkill/im chrome.exe /f")

我无法访问带有Windows的计算机,但它应该可以正常工作。

编辑:

另请尝试:

1-命令在taskkill和/ IM之间需要一个空格,所以:

 os.system("taskkill /im chrome.exe /f")

2- Taskkill is not in Windows XP, there ais a less powerfull tool called tskill所以:

os.system("tskill chrome")

答案 1 :(得分:0)

如上面链接到RvdK的问题所述:你需要一个完全限定的taskkill.exe路径,但没有提到你需要记住逃避反斜杠的事实,所以

call("c:\\windows\\system32\\taskkill.exe /im chrome.exe /f", shell=True)

应该可以工作(它在我的Win7机器上运行)。

请注意,您实际上需要 shell=True位,如subprocess文档中所述:

  

在具有shell = True的Windows上,COMSPEC环境变量指定   默认的shell。您唯一需要指定shell = True的时间   Windows是您希望执行的命令内置于   shell(例如dir或copy)。您不需要shell = True来运行批处理   文件或基于控制台的可执行文件。

所以call("c:\\windows\\system32\\taskkill.exe /im chrome.exe /f")更好。

答案 2 :(得分:0)

#我的备忘录

from win32com.client import GetObject
import os

WMI = GetObject('winmgmts:')
for p in WMI.ExecQuery('select * from Win32_Process where Name LIKE "%chrome%"'):
    os.system("taskkill /F /PID "+str(p.ProcessId))