Skip to content

Commit

Permalink
Simplify command discovery with stdlib shutil.which()
Browse files Browse the repository at this point in the history
Use the builtin shutil.which() instead of reimplementing.

For the single use that used the output of the command, use
subprocess.run().
  • Loading branch information
jdufresne committed Feb 14, 2020
1 parent 098406c commit e544fd5
Showing 1 changed file with 11 additions and 21 deletions.
32 changes: 11 additions & 21 deletions Tests/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import logging
import os
import shutil
import subprocess
import sys
import tempfile
Expand Down Expand Up @@ -191,9 +192,12 @@ def open_withImagemagick(self, f):
raise OSError()

outfile = self.tempfile("temp.png")
if command_succeeds([IMCONVERT, f, outfile]):
return Image.open(outfile)
raise OSError()
rc = subprocess.call(
[IMCONVERT, f, outfile], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT
)
if rc:
raise OSError
return Image.open(outfile)


@unittest.skipIf(sys.platform.startswith("win32"), "requires Unix or macOS")
Expand Down Expand Up @@ -268,34 +272,20 @@ def hopper(mode=None, cache={}):
return im.copy()


def command_succeeds(cmd):
"""
Runs the command, which must be a list of strings. Returns True if the
command succeeds, or False if an OSError was raised by subprocess.Popen.
"""
try:
subprocess.call(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
except OSError:
return False
return True


def djpeg_available():
return command_succeeds(["djpeg", "-version"])
return bool(shutil.which("djpeg"))


def cjpeg_available():
return command_succeeds(["cjpeg", "-version"])
return bool(shutil.which("cjpeg"))


def netpbm_available():
return command_succeeds(["ppmquant", "--version"]) and command_succeeds(
["ppmtogif", "--version"]
)
return bool(shutil.which("ppmquant") and shutil.which("ppmtogif"))


def imagemagick_available():
return IMCONVERT and command_succeeds([IMCONVERT, "-version"])
return bool(IMCONVERT and shutil.which(IMCONVERT))


def on_appveyor():
Expand Down

0 comments on commit e544fd5

Please sign in to comment.