Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

closes #1173 - backporting python2.7 subprocess's check_output to be abl... #1174

Merged
merged 3 commits into from Sep 1, 2012
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 7 additions & 5 deletions lib/matplotlib/backends/backend_pgf.py
Expand Up @@ -19,6 +19,8 @@
from matplotlib import font_manager
from matplotlib.ft2font import FT2Font
from matplotlib.cbook import is_string_like, is_writable_file_like
from matplotlib.cbook import check_output


###############################################################################

Expand Down Expand Up @@ -150,14 +152,14 @@ def make_pdf_to_png_converter():
tools_available = []
# check for pdftocairo
try:
subprocess.check_output(["pdftocairo", "-v"], stderr=subprocess.STDOUT)
check_output(["pdftocairo", "-v"], stderr=subprocess.STDOUT)
tools_available.append("pdftocairo")
except:
pass
# check for ghostscript
try:
gs = "gs" if sys.platform is not "win32" else "gswin32c"
subprocess.check_output([gs, "-v"], stderr=subprocess.STDOUT)
check_output([gs, "-v"], stderr=subprocess.STDOUT)
tools_available.append("gs")
except:
pass
Expand All @@ -168,15 +170,15 @@ def cairo_convert(pdffile, pngfile, dpi):
cmd = ["pdftocairo", "-singlefile", "-png",
"-r %d" % dpi, pdffile, os.path.splitext(pngfile)[0]]
# for some reason this doesn't work without shell
subprocess.check_output(" ".join(cmd), shell=True, stderr=subprocess.STDOUT)
check_output(" ".join(cmd), shell=True, stderr=subprocess.STDOUT)
return cairo_convert
elif "gs" in tools_available:
def gs_convert(pdffile, pngfile, dpi):
cmd = [gs, '-dQUIET', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-dNOPROMPT',
'-sDEVICE=png16m', '-dUseCIEColor', '-dTextAlphaBits=4',
'-dGraphicsAlphaBits=4', '-dDOINTERPOLATE', '-sOutputFile=%s' % pngfile,
'-r%d' % dpi, pdffile]
subprocess.check_output(cmd, stderr=subprocess.STDOUT)
check_output(cmd, stderr=subprocess.STDOUT)
return gs_convert
else:
raise RuntimeError("No suitable pdf to png renderer found.")
Expand Down Expand Up @@ -719,7 +721,7 @@ def _print_pdf_to_fh(self, fh):
texcommand = get_texcommand()
cmdargs = [texcommand, "-interaction=nonstopmode", "-halt-on-error", "figure.tex"]
try:
subprocess.check_output(cmdargs, stderr=subprocess.STDOUT)
check_output(cmdargs, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
raise RuntimeError("%s was not able to process your file.\n\nFull log:\n%s" % (texcommand, e.output))

Expand Down
45 changes: 44 additions & 1 deletion lib/matplotlib/cbook.py
Expand Up @@ -12,9 +12,10 @@
from weakref import ref, WeakKeyDictionary
import cPickle
import os.path
import random
from functools import reduce

import subprocess

import matplotlib

major, minor1, minor2, s, tmp = sys.version_info
Expand Down Expand Up @@ -1897,6 +1898,48 @@ def _putmask(a, mask, values):
return np.copyto(a, values, where=mask)


def _check_output(*popenargs, **kwargs):
r"""Run command with arguments and return its output as a byte
string.

If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the
returncode
attribute and output in the output attribute.

The arguments are the same as for the Popen constructor. Example:

>>> check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'

The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.

>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
'ls: non_existent_file: No such file or directory\n'
"""
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise subprocess.CalledProcessError(retcode, cmd, output=output)
return output


# python2.7's subprocess provides a check_output method
if hasattr(subprocess, 'check_output'):
check_output = subprocess.check_output
else:
check_output = _check_output


if __name__=='__main__':
assert( allequal([1,1,1]) )
assert(not allequal([1,1,0]) )
Expand Down
7 changes: 7 additions & 0 deletions lib/matplotlib/tests/test_backend_pgf.py
Expand Up @@ -13,6 +13,7 @@

baseline_dir, result_dir = _image_directories(lambda: 'dummy func')


def check_for(texsystem):
header = r"""
\documentclass{minimal}
Expand All @@ -32,6 +33,7 @@ def check_for(texsystem):

return latex.returncode == 0


def switch_backend(backend):

def switch_backend_decorator(func):
Expand All @@ -48,6 +50,7 @@ def backend_switcher(*args, **kwargs):
return nose.tools.make_decorator(func)(backend_switcher)
return switch_backend_decorator


def compare_figure(fname):
actual = os.path.join(result_dir, fname)
plt.savefig(actual)
Expand Down Expand Up @@ -126,3 +129,7 @@ def test_rcupdate():
mpl.rcParams.update(rc_set)
create_figure()
compare_figure('pgf_rcupdate%d.pdf' % (i+1))

if __name__ == '__main__':
import nose
nose.runmodule(argv=['-s','--with-doctest'], exit=False)