2015-08-18 53 views
0

所以我有一個測試運行一個後臺進程,並在測試結束時停止它,但是在Travis中運行時遇到了一些麻煩。它有點像這樣,在Travis CI環境中用python殺死一個進程

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,但是當我把代碼,使其觸發一個特拉維斯CI建立它失敗,因爲後臺進程沒有停止,並開始相互矛盾的我的github倉庫與其他測試。經過一些調試後,看起來output變量只是一個空字符串,即代碼無法找到後臺進程。所以也許我真正的問題是如何列出Travis中的流程?

道歉我剛剛在這裏寫了大部分的代碼,有一些複製和粘貼來演示這個問題,所以可能有錯別字或其他東西我錯過了,我會嘗試設置一個可重現的錯誤,但希望這裏有足夠的信息?

回答

0

已解決。

通過保持對Popen對象的引用,我可以通過python殺死進程而無需訪問os。

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'])