在Travis CI环境中使用python杀死进程

时间:2015-08-18 15:00:37

标签: python travis-ci python-unittest

所以我有一个运行后台进程的测试并在测试结束时停止它,但是当它在Travis中运行时我遇到了一些麻烦。它有点像这样,

import unittest
import subprocess, os, signal

class MyTest(unittest.TestCase):
    def tearDown(self):
        # tactic: look for the background command using the shell ps command
        # and kill that process using os.kill (running on Debian)
        process1 = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
        process2 = subprocess.Popen(['grep', 'python manage.py my_background_process'], stdin=process1.stdout, stdout=subprocess.PIPE)
        # my_background_process is a custom django command, I don't think that is relevant though
        process1.stdout.close()
        output = process2.communicate()[0] # output from the grep command
        for line in output.split('\n'):
            if line != '' and 'grep' not in line: # ignore the grep command and non-existent process
                pid = int(line.strip().split(' ')[0]) # pid in the first part of the string
                os.kill(pid, signal.SIGTERM)

    def test_one(self):
        subprocess.Popen(['python', 'manage.py', 'my_background_process'])

    def test_two(self):
        subprocess.Popen(['python', 'manage.py', 'my_background_process'])

这里的自定义django命令非常简单,例如my_background_process.py

import time

while True:
    f = open('test_file.txt', 'wb')
    f.close()

这一切都适用于运行Mac OSX的本地计算机,但是当我将代码推送到触发Travis CI构建的github存储库时,它会失败,因为后台进程没有停止并且开始与其他测试冲突。经过一些调试后,output变量似乎只是一个空字符串,即代码无法找到后台进程。那么也许我真正的问题是如何列出特拉维斯的流程?

道歉我刚刚在这里编写了大部分代码,并通过一些复制和粘贴来演示问题,因此可能存在拼写错误或其他我错过的内容,我会尝试设置一个可重现的错误但希望这里有足够的信息?

1 个答案:

答案 0 :(得分:0)

解决。

通过保持对Popen对象的引用,我可以通过python终止进程而无需访问操作系统。

import unittest
import subprocess, os, signal

class MyTest(unittest.TestCase):
    def tearDown(self):
        self.bg_process.kill()

    def test_one(self):
        self.bg_process = subprocess.Popen(['python', 'manage.py', 'my_background_process'])

    def test_two(self):
        self.bg_process = subprocess.Popen(['python', 'manage.py', 'my_background_process'])