Python中跨平台终止进程的方法

2 投票
1 回答
2396 浏览
提问于 2025-04-15 15:42

我在Windows系统中尝试用subprocess.Popen.terminate()或kill()命令结束一个进程时,遇到了“访问被拒绝”的错误。我真的需要一种跨平台的方法来终止这个进程,前提是那个文件不再存在(是的,我知道这样做不是最优雅的方式),我希望尽量不使用平台特定的调用或者导入win32api。

另外,一旦我结束了这个任务,我应该可以直接删除这个库的那部分吧?(我记得之前看到过,如果我打算在工作时修改某些东西,可能需要使用切片?)

#/usr/bin/env python
#import sys
import time
import os
import subprocess
import platform

ServerRange = range(7878, 7890)  #Range of ports you want your server to use.
cmd = 'VoiceChatterServer.exe'

#********DO NOT EDIT BELOW THIS LINE*******

def Start_IfConfExist(i):
    if os.path.exists(str(i) + ".conf"):
        Process[i] = subprocess.Popen(" " + cmd + " --config " + str(i) + ".conf", shell=True)

Process = {}

for i in ServerRange:
    Start_IfConfExist(i)

while True:
    for i in ServerRange:
        if os.path.exists(str(i) + ".conf"):
            res = Process[i].poll()
        if not os.path.exists(str(i) + ".conf"):  #This is the problem area
            res = Process[i].terminate()          #This is the problem area.
        if res is not None:
            Start_IfConfExist(i)
            print "\nRestarting: " + str(i) + "\n"
    time.sleep(1)

1 个回答

2

你可以通过做一些简单的事情,轻松实现跨平台的调用,比如:

try:
    import win32
    def kill(param):
        # the code from S.Lotts link
except ImportError:
    def kill(param):
        # the unix way

至于为什么Python默认没有这个功能,我也不知道。不过在其他领域,比如文件变化通知,也存在类似的问题,实际上制作一个跨平台的库并不难(至少可以在Windows、Mac和Linux上用)。我想因为它是开源的,所以你得自己动手去解决这个问题 :P

撰写回答