我正在编写一个用于连续集成和测试的python脚本,该脚本将由bitten调用。我们的单元测试使用Google测试框架。每个软件组件都有一个BASH脚本,该脚本运行配置和其他必需的服务,并运行GTEST可执行文件。Python脚本在存储库中寻找BASH脚本,并使用OS.Popen()命令调用每个脚本。
python脚本(unittest.py)
#!/usr/bin/python
import os
import fnmatch
import sys
import subprocess
repository_location = '/home/actuv/workspace/eclipse/iccs/'
unit_test_script_name = 'RunUnitTests.sh'
def file_locator(repo, script_name):
# Function for determining all unit test scripts
test_location = []
for root, dirnames, filenames in os.walk(repo):
for filename in fnmatch.filter(filenames, script_name):
test_location.append(os.path.join(root))
return test_location
def run_tests(test_locations, script_name):
# Runs test scripts located at each test location
for tests in test_locations:
cmd = 'cd ' + tests + ';./' + script_name
print 'Running Unit Test at: ' + tests
os.popen(cmd)
################ MAIN ################
# Find Test Locations
script_locations = file_locator(repository_location, unit_test_script_name)
# Run tests located at each location
run_tests(script_locations)
# End of tests
sys.exit(0)
bash脚本
#!/bin/sh
echo "Running unit tests..."
# update the LD_LIBRARY_PATH to include paths to our shared libraries
# start the test server
# Run the tests
# wait to allow all processes to end before terminating the server
sleep 10s
当我从终端窗口手动运行BASH脚本时,它运行良好。当我有Python脚本调用bash脚本时,我会在bash脚本的testsingleclient和testmulticlientla线上得到一个分割故障。
尝试更换
os.popen(cmd)
proc = subprocess.Popen('./scriptname', shell = True,
cwd = tests)
proc.communicate()
绝对查看子进程模块 - 特别是查看 subprocess.call()便利方法。我投入了操作系统检查,以确保您的测试目录也存在。
def run_tests(test_locations, script_name):
# Runs test scripts located at each test location
for tests in test_locations:
# Make sure tests directory exists and is a dir
if os.path.isdir(tests):
print 'Running Unit Test at: ' + tests
subprocess.call(script_name, shell=True, cwd=tests)
另外 - 您对Stdout和Stderr的观察是正确的,尤其是在有很多数据时。当有大量或未知数的输出时,我将temp文件用于stdout/stderr。
例如。
def execute_some_command(cmd="arbitrary_exe"):
""" Execute some command using subprocess.call()"""
# open/create temportary file for stdout
tmp_out=file('.tmp','w+')
# Run command, pushing stdout to tmp_out file handle
retcode = subprocess.call(cmd, stdout=tmp_out, shell=True)
if retcode != 0:
# do something useful (like bailout) based on the OS return code
print "FAILED"
# Flush any queued data
tmp_out.flush()
# Jump to the beginning
tmp_out.seek(0)
# Parse output
for line in tmp_out.readlines():
# do something useful with output
# cleanup
tmp_out.close()
os.remove(_out.name)
return
查看python文件对象上的方法,以了解如何从 _OUT 文件句柄中处理您的Stdout数据。
良好的狩猎。