如何在不终止当前进程的情况下杀死窗口中的进程

时间:2020-06-13 16:11:30

标签: python cmd process

你好,我只是想杀死一个进程而不杀死当前进程,前提是我有一个python代码,可以在txt文件中写一个字符串,例如

import os
while True:
    with open('input.txt' , 'r') as re:
        all_data = re.read()
    if all_data == 'pause':
        os.system('kill.bat')
    else:
        print("\nContinue\n")

在这里它将读取input.txt,如果它等于暂停,那么它将在此处运行kill.bat。我想为此重新启动该代码,我将编写另一个脚本kill.bat,重新启动该代码,但是问题出在是不是因为它正在杀死kill.bat文件而没有重新启动,但是我不会只杀死python终端并重新启动它,在这里我是怎么做的kill.bat文件代码

taskkill /IM cmd.exe
python main.py

main.py是我的python文件

1 个答案:

答案 0 :(得分:0)

不错的尝试@Pryanshu

您做对了。您当前方法的问题是python,而批处理脚本将处于同一进程中,并同时被杀死。 因此,只需稍微改变一下方法

要点:

python

get current process id
while loop 
    read file
    if matches condition
        call kill.bat and pass this python process ID as separate process

批处理

get first parameter (which is the python process to kill)
kill the process via taskkill
start the python script as seprate process
exit

助手

get current process ID     - pid = os.getpid()
pass id to batch script    - os.system("kill.bat %s" % pid)
batch script get arguments - %1
                             this %1 will contain the first argument passed. 
                             by default %* will contain all the arguments passed to the script.
python start program as 
separate process           - use subprocess python package
cmd start program as 
separate process           - use Start command
kill process via taskkill  - taskkill /F /PID <pid>
                             replace <pid> with your argument

我知道您可以处理代码部分。您必须使用 Helpers 并将它们组合在一起以完成任务。 Lemme知道输出。

如果您有任何问题,请发表评论。我会尽快回复

欢呼

相关问题