Skip to content

Commit e544fd5

Browse files
committed
Simplify command discovery with stdlib shutil.which()
Use the builtin shutil.which() instead of reimplementing. For the single use that used the output of the command, use subprocess.run().
1 parent 098406c commit e544fd5

1 file changed

Lines changed: 11 additions & 21 deletions

File tree

Tests/helper.py

Lines changed: 11 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import logging
66
import os
7+
import shutil
78
import subprocess
89
import sys
910
import tempfile
@@ -191,9 +192,12 @@ def open_withImagemagick(self, f):
191192
raise OSError()
192193

193194
outfile = self.tempfile("temp.png")
194-
if command_succeeds([IMCONVERT, f, outfile]):
195-
return Image.open(outfile)
196-
raise OSError()
195+
rc = subprocess.call(
196+
[IMCONVERT, f, outfile], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT
197+
)
198+
if rc:
199+
raise OSError
200+
return Image.open(outfile)
197201

198202

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

270274

271-
def command_succeeds(cmd):
272-
"""
273-
Runs the command, which must be a list of strings. Returns True if the
274-
command succeeds, or False if an OSError was raised by subprocess.Popen.
275-
"""
276-
try:
277-
subprocess.call(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
278-
except OSError:
279-
return False
280-
return True
281-
282-
283275
def djpeg_available():
284-
return command_succeeds(["djpeg", "-version"])
276+
return bool(shutil.which("djpeg"))
285277

286278

287279
def cjpeg_available():
288-
return command_succeeds(["cjpeg", "-version"])
280+
return bool(shutil.which("cjpeg"))
289281

290282

291283
def netpbm_available():
292-
return command_succeeds(["ppmquant", "--version"]) and command_succeeds(
293-
["ppmtogif", "--version"]
294-
)
284+
return bool(shutil.which("ppmquant") and shutil.which("ppmtogif"))
295285

296286

297287
def imagemagick_available():
298-
return IMCONVERT and command_succeeds([IMCONVERT, "-version"])
288+
return bool(IMCONVERT and shutil.which(IMCONVERT))
299289

300290

301291
def on_appveyor():

0 commit comments

Comments
 (0)