开发者

Cross-platform way to terminate a process in python

When I try to kill a process in windows with the subprocess.Popen.terminate() or kill() commands, I get an access denied error. I really need a cross-platform way to terminate the process if the file no longer exists (Yes, I know it's not the most elegant way of doing what I'm doing), I don't want to have to use platform calls or import win32api if at all possible.

Also - Once I kill the task, I should be able to just delete the iteration of that portion of the library, no? (I remember reading something about having to use slice if I plan on working on something and modifying it while working on it?)

#/usr/bin/env python
#import开发者_StackOverflow社区 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)


You can easily make a platform independent call by doing something trivial like:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜