fix: no check_output in py 2.6

This commit is contained in:
Luke Campagnola 2016-02-12 17:51:34 -08:00
parent f2a72bf780
commit 879f341913

View File

@ -44,7 +44,7 @@ import os
import sys import sys
import inspect import inspect
import base64 import base64
from subprocess import check_call, check_output, CalledProcessError import subprocess as sp
import numpy as np import numpy as np
#from ..ext.six.moves import http_client as httplib #from ..ext.six.moves import http_client as httplib
@ -224,7 +224,7 @@ def assertImageMatch(im1, im2, minCorr=0.9, pxThreshold=50.,
def saveFailedTest(data, expect, filename): def saveFailedTest(data, expect, filename):
"""Upload failed test images to web server to allow CI test debugging. """Upload failed test images to web server to allow CI test debugging.
""" """
commit, error = check_output(['git', 'rev-parse', 'HEAD']) commit, error = runSubprocess(['git', 'rev-parse', 'HEAD'])
name = filename.split('/') name = filename.split('/')
name.insert(-1, commit.strip()) name.insert(-1, commit.strip())
filename = '/'.join(name) filename = '/'.join(name)
@ -389,7 +389,7 @@ def getTestDataRepo():
except NameError: except NameError:
cmd = gitbase + ['fetch', '--tags', 'origin'] cmd = gitbase + ['fetch', '--tags', 'origin']
print(' '.join(cmd)) print(' '.join(cmd))
check_call(cmd) sp.check_call(cmd)
try: try:
tagCommit = gitCommitId(dataPath, testDataTag) tagCommit = gitCommitId(dataPath, testDataTag)
except NameError: except NameError:
@ -406,7 +406,7 @@ def getTestDataRepo():
# If HEAD is not the correct commit, then do a checkout # If HEAD is not the correct commit, then do a checkout
if gitCommitId(dataPath, 'HEAD') != tagCommit: if gitCommitId(dataPath, 'HEAD') != tagCommit:
print("Checking out test-data tag '%s'" % testDataTag) print("Checking out test-data tag '%s'" % testDataTag)
check_call(gitbase + ['checkout', testDataTag]) sp.check_call(gitbase + ['checkout', testDataTag])
else: else:
print("Attempting to create git clone of test data repo in %s.." % print("Attempting to create git clone of test data repo in %s.." %
@ -433,7 +433,7 @@ def getTestDataRepo():
for cmd in cmds: for cmd in cmds:
print(' '.join(cmd)) print(' '.join(cmd))
rval = check_call(cmd) rval = sp.check_call(cmd)
if rval == 0: if rval == 0:
continue continue
raise RuntimeError("Test data path '%s' does not exist and could " raise RuntimeError("Test data path '%s' does not exist and could "
@ -453,7 +453,7 @@ def gitStatus(path):
repository. repository.
""" """
cmd = gitCmdBase(path) + ['status', '--porcelain'] cmd = gitCmdBase(path) + ['status', '--porcelain']
return check_output(cmd, stderr=None, universal_newlines=True) return runSubprocess(cmd, stderr=None, universal_newlines=True)
def gitCommitId(path, ref): def gitCommitId(path, ref):
@ -461,8 +461,8 @@ def gitCommitId(path, ref):
""" """
cmd = gitCmdBase(path) + ['show', ref] cmd = gitCmdBase(path) + ['show', ref]
try: try:
output = check_output(cmd, stderr=None, universal_newlines=True) output = runSubprocess(cmd, stderr=None, universal_newlines=True)
except CalledProcessError: except sp.CalledProcessError:
print(cmd) print(cmd)
raise NameError("Unknown git reference '%s'" % ref) raise NameError("Unknown git reference '%s'" % ref)
commit = output.split('\n')[0] commit = output.split('\n')[0]
@ -470,56 +470,46 @@ def gitCommitId(path, ref):
return commit[7:] return commit[7:]
#import subprocess def runSubprocess(command, return_code=False, **kwargs):
#def run_subprocess(command, return_code=False, **kwargs): """Run command using subprocess.Popen
#"""Run command using subprocess.Popen
Similar to subprocess.check_output(), which is not available in 2.6.
#Run command and wait for command to complete. If the return code was zero Run command and wait for command to complete. If the return code was zero
#then return, otherwise raise CalledProcessError. then return, otherwise raise CalledProcessError.
#By default, this will also add stdout= and stderr=subproces.PIPE By default, this will also add stdout= and stderr=subproces.PIPE
#to the call to Popen to suppress printing to the terminal. to the call to Popen to suppress printing to the terminal.
#Parameters Parameters
#---------- ----------
#command : list of str command : list of str
#Command to run as subprocess (see subprocess.Popen documentation). Command to run as subprocess (see subprocess.Popen documentation).
#return_code : bool **kwargs : dict
#If True, the returncode will be returned, and no error checking Additional kwargs to pass to ``subprocess.Popen``.
#will be performed (so this function should always return without
#error).
#**kwargs : dict
#Additional kwargs to pass to ``subprocess.Popen``.
#Returns Returns
#------- -------
#stdout : str stdout : str
#Stdout returned by the process. Stdout returned by the process.
#stderr : str """
#Stderr returned by the process. # code adapted with permission from mne-python
#code : int use_kwargs = dict(stderr=None, stdout=sp.PIPE)
#The command exit code. Only returned if ``return_code`` is True. use_kwargs.update(kwargs)
#"""
## code adapted with permission from mne-python
#use_kwargs = dict(stderr=subprocess.PIPE, stdout=subprocess.PIPE)
#use_kwargs.update(kwargs)
#p = subprocess.Popen(command, **use_kwargs) p = sp.Popen(command, **use_kwargs)
#output = p.communicate() output = p.communicate()[0]
## communicate() may return bytes, str, or None depending on the kwargs # communicate() may return bytes, str, or None depending on the kwargs
## passed to Popen(). Convert all to unicode str: # passed to Popen(). Convert all to unicode str:
#output = ['' if s is None else s for s in output] output = '' if output is None else output
#output = [s.decode('utf-8') if isinstance(s, bytes) else s for s in output] output = output.decode('utf-8') if isinstance(output, bytes) else output
#output = tuple(output)
#if not return_code and p.returncode: if p.returncode != 0:
#print(output[0]) print(output)
#print(output[1]) err_fun = sp.CalledProcessError.__init__
#err_fun = subprocess.CalledProcessError.__init__ if 'output' in inspect.getargspec(err_fun).args:
#if 'output' in inspect.getargspec(err_fun).args: raise sp.CalledProcessError(p.returncode, command, output)
#raise subprocess.CalledProcessError(p.returncode, command, output) else:
#else: raise sp.CalledProcessError(p.returncode, command)
#raise subprocess.CalledProcessError(p.returncode, command)
#if return_code: return output
#output = output + (p.returncode,)
#return output