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
#Run command and wait for command to complete. If the return code was zero Similar to subprocess.check_output(), which is not available in 2.6.
#then return, otherwise raise CalledProcessError.
#By default, this will also add stdout= and stderr=subproces.PIPE
#to the call to Popen to suppress printing to the terminal.
#Parameters Run command and wait for command to complete. If the return code was zero
#---------- then return, otherwise raise CalledProcessError.
#command : list of str By default, this will also add stdout= and stderr=subproces.PIPE
#Command to run as subprocess (see subprocess.Popen documentation). to the call to Popen to suppress printing to the terminal.
#return_code : bool
#If True, the returncode will be returned, and no error checking
#will be performed (so this function should always return without
#error).
#**kwargs : dict
#Additional kwargs to pass to ``subprocess.Popen``.
#Returns Parameters
#------- ----------
#stdout : str command : list of str
#Stdout returned by the process. Command to run as subprocess (see subprocess.Popen documentation).
#stderr : str **kwargs : dict
#Stderr returned by the process. Additional kwargs to pass to ``subprocess.Popen``.
#code : int
#The command exit code. Only returned if ``return_code`` is True.
#"""
## 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) Returns
#output = p.communicate() -------
stdout : str
Stdout returned by the process.
"""
# code adapted with permission from mne-python
use_kwargs = dict(stderr=None, stdout=sp.PIPE)
use_kwargs.update(kwargs)
## communicate() may return bytes, str, or None depending on the kwargs p = sp.Popen(command, **use_kwargs)
## passed to Popen(). Convert all to unicode str: output = p.communicate()[0]
#output = ['' if s is None else s for s in output]
#output = [s.decode('utf-8') if isinstance(s, bytes) else s for s in output]
#output = tuple(output)
#if not return_code and p.returncode: # communicate() may return bytes, str, or None depending on the kwargs
#print(output[0]) # passed to Popen(). Convert all to unicode str:
#print(output[1]) output = '' if output is None else output
#err_fun = subprocess.CalledProcessError.__init__ output = output.decode('utf-8') if isinstance(output, bytes) else output
#if 'output' in inspect.getargspec(err_fun).args:
#raise subprocess.CalledProcessError(p.returncode, command, output) if p.returncode != 0:
#else: print(output)
#raise subprocess.CalledProcessError(p.returncode, command) err_fun = sp.CalledProcessError.__init__
#if return_code: if 'output' in inspect.getargspec(err_fun).args:
#output = output + (p.returncode,) raise sp.CalledProcessError(p.returncode, command, output)
#return output else:
raise sp.CalledProcessError(p.returncode, command)
return output