Raise error if unable to open X server

This commit is contained in:
Andrew Murray 2020-03-24 20:20:08 +11:00
parent 13ab784c51
commit b182621c59
2 changed files with 23 additions and 13 deletions

View File

@ -2,24 +2,29 @@ import subprocess
import sys import sys
import pytest import pytest
from PIL import ImageGrab
from .helper import assert_image from .helper import assert_image
from PIL import ImageGrab
class TestImageGrab: class TestImageGrab:
def test_grab(self): def test_grab(self):
if sys.platform in ["darwin", "win32"] or ImageGrab._has_imagemagick(): native_support = sys.platform in ["darwin", "win32"]
for im in [ if native_support or ImageGrab._has_imagemagick():
ImageGrab.grab(), for args in [
ImageGrab.grab(include_layered_windows=True), {},
ImageGrab.grab(all_screens=True), {"include_layered_windows": True},
{"all_screens": True},
{"bbox": (10, 20, 50, 80)},
]: ]:
assert_image(im, im.mode, im.size) try:
im = ImageGrab.grab(**args)
im = ImageGrab.grab(bbox=(10, 20, 50, 80)) except IOError as e:
assert_image(im, im.mode, (40, 60)) if not native_support and str(e) == "Unable to open X server":
continue
else:
raise
assert_image(im, im.mode, (40, 60) if "bbox" in args else im.size)
else: else:
pytest.raises(IOError, ImageGrab.grab) pytest.raises(IOError, ImageGrab.grab)
@ -36,7 +41,7 @@ $bmp = New-Object Drawing.Bitmap 200, 200
) )
p.communicate() p.communicate()
else: else:
self.assertRaises(NotImplementedError, ImageGrab.grabclipboard) pytest.raises(NotImplementedError, ImageGrab.grabclipboard)
return return
im = ImageGrab.grabclipboard() im = ImageGrab.grabclipboard()

View File

@ -68,7 +68,12 @@ def grab(bbox=None, include_layered_windows=False, all_screens=False):
raise IOError("grab requires ImageMagick unless used on macOS or Windows") raise IOError("grab requires ImageMagick unless used on macOS or Windows")
fh, filepath = tempfile.mkstemp(".png") fh, filepath = tempfile.mkstemp(".png")
os.close(fh) os.close(fh)
subprocess.call(["import", "-window", "root", filepath])
p = subprocess.Popen(
["import", "-window", "root", filepath], stderr=subprocess.PIPE
)
if b"unable to open X server" in p.communicate()[1]:
raise IOError("Unable to open X server")
im = Image.open(filepath) im = Image.open(filepath)
im.load() im.load()
os.unlink(filepath) os.unlink(filepath)