简体   繁体   English

Python杀死没有外壳的进程

[英]Python kill a process without a shell

I am making a program to do a bit of process management for me on windows 10. 我正在编写一个程序来在Windows 10上为我做一些过程管理。

In order to kill unneeded processes I am using the following command: 为了杀死不需要的进程,我使用以下命令:

import subprocess
subprocess.Popen("taskkill /F /im "+unwantedProcess, shell=True, stdout=subprocess.PIPE)

Where unwanted process is the full name of a process I want to kill. 不需要的进程是我要杀死的进程的全名。 I have also tried using: 我也尝试过使用:

os.system("taskkill /F /im "+unwantedProcess)

Now this works fine when it is interpreted or compiled using pyinstaller. 现在,使用pyinstaller解释或编译它时,它可以正常工作。 The problem comes when I use the 问题出在我使用

--noconsole

command in pyinstaller. pyinstaller中的命令。 It works in all other instances except when there in no console (since I do not want a console opened in the background). 它适用于所有其他实例,除非没有控制台(因为我不希望在后台打开控制台)。 Any idea how to fix this? 任何想法如何解决这个问题?

Edit: After editing the code I inserted a very basic error catch statement as follows: 编辑:编辑代码后,我插入了一个非常基本的错误捕获语句,如下所示:

try:
    subprocess.Popen("taskkill /F /im skype.exe", shell=True, stdout=subprocess.PIPE)
except Exception as e:
    f = open("error.txt", "w")
    f.write(str(e))
    f.close()

Using skype as an example process to kill. 以Skype为例进行杀死。 It still killed it successfully when the program was interpreted or compiled with a console. 当使用控制台解释或编译程序时,它仍然可以成功杀死它。 However, when it was compiled using the 但是,当使用

--noconsole

command once again I got this output in my error file: 命令再次在错误文件中得到以下输出:

[Error 6] The handle is invalid

Skype was definitely open when I ran this program 当我运行该程序时,Skype肯定是开放的

The fact that you are calling python with the --no-console option makes your process not suitable for console I/O (ie what you need to call taskkill ). 您使用--no-console选项调用python的事实使您的进程不适合控制台I / O(即,您需要调用taskkill )。

If you really want to hide the console and still have a valid process handle, there are different ways to do it. 如果您确实想隐藏控制台并仍然具有有效的进程句柄,则可以使用不同的方法。 Look at the answers for this question 这个问题的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM