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

2024-06-08

当我尝试使用 subprocess.Popen.terminate() 或 Kill() 命令终止 Windows 中的进程时,出现访问被拒绝错误。如果文件不再存在,我真的需要一种跨平台的方式来终止进程(是的,我知道这不是做我正在做的事情的最优雅的方式),我不想使用平台调用或如果可能的话导入 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)

您可以通过执行以下简单操作来轻松进行独立于平台的调用:

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

为什么默认情况下 python 中不存在这个问题我不知道,但是在其他领域也存在非常类似的问题,例如文件更改通知,制作一个独立于平台的库(或者至少是 win+mac)确实并不难+Linux)。我想它是开源的,所以你必须自己修复它:P

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python中终止进程的跨平台方法 的相关文章

随机推荐