2

当我尝试使用 subprocess.Popen.terminate() 或 kill() 命令在 Windows 中终止进程时,我收到拒绝访问错误。如果文件不再存在,我真的需要一种跨平台的方式来终止进程(是的,我知道这不是我正在做的最优雅的方式),我不想使用平台调用或如果可能,请导入 win32api。

另外 - 一旦我终止任务,我应该能够删除库的那部分的迭代,不是吗?(我记得读过一些关于必须使用 slice 的文章,如果我打算处理某事并在处理它的同时对其进行修改?)

#/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)
4

1 回答 1

2

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

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

Why this doesn't exist in python by default I don't know, but there are very similar problems in other areas like file change notifications where it really isn't that hard to make a platform independent lib (or at least win+mac+linux). I guess it's open source so you have to fix it yourself :P

于 2009-11-05T18:15:58.260 回答