完成后启动子流程并保存以杀死

时间:2016-01-23 09:56:06

标签: python subprocess

我做了一个课程来开始一些程序,并在我完成任务时终止。 但似乎好转。它具有设置和拆卸功能以及存储过程的变量。

我不关心stdout& stderr现在。我只是认为我需要包含它。

class ServerClient(object):

    def __init__(self):
        self.server_process = None
        self.client_process = None

    def setUp(self):
        self.server_process = subprocess.Popen(
                ['python', 'servlet.py'],
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
        )
        self.client_process = subprocess.Popen(
                ['python', 'client.py'],
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
        )
        time.sleep(2)

    def tearDown(self):
        if self.server_process is not None:
            try:
                print "Killing Server"
                self.server_process.terminate()
                self.server_process.wait()
            except OSError:
                pass
            self.server_process = None
        if self.client_process is not None:
            try:
                print "Killing Client"
                self.client_process.terminate()
                self.client_process.wait()
            except OSError:
                pass
            self.client_process = None

if __name__ == '__main__':
    sc = ServerClient()
    sc.setUp()
    # Do stuff
    sc.tearDown()

1 个答案:

答案 0 :(得分:1)

(在POSIX OS上)terminate()将SIGTERM发送给进程。尝试

angular.module('myApp', []).directive('uiFoo',
  function() {
    return {
      restrict: 'EAC',
      link: function($scope, element, attrs, controller) {
        $scope.foo = attrs.uiFoo;
      }
    };
  }
);

如果服务器或客户端需要生成进程,则必须以不同方式调用Popen并使用os.killpg。

import os
import signal

os.kill(self.server_process.pid, signal.SIGTERM)
os.kill(self.server_process.pid, signal.SIGTERM)