如何修复KeyError:' DISPLAY'在Python中

时间:2018-03-15 20:09:14

标签: python python-3.x python-mss

我在Python中使用mss库来截取屏幕截图并将其保存在当前路径中。它使用PyCharm在我的Mac上完美运行。但是当我尝试在Ubuntu 16上运行同样的东西时,我得到一个错误,即使我正在完成Docs所说的那样:

>>> from mss import mss
>>> with mss() as sct:
...     sct.shot()

但我收到此错误,如何解决此问题?

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/mss/linux.py", line 132, in __init__
    display = os.environ['DISPLAY'].encode('utf-8')
  File "/usr/lib/python3.5/os.py", line 725, in __getitem__
    raise KeyError(key) from None
KeyError: 'DISPLAY'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/mss/factory.py", line 34, in mss
    return MSS(**kwargs)
  File "/usr/local/lib/python3.5/dist-packages/mss/linux.py", line 134, in __init__
    raise ScreenShotError('$DISPLAY not set.', locals())
mss.exception.ScreenShotError: ('$DISPLAY not set.', {'display': None, 'self': <mss.linux.MSS object at 0x7f06ce881d30>})

1 个答案:

答案 0 :(得分:0)

的确,在GNU / Linux上,您必须设置DISPLAY envar。如果没有,则不常见,您可以尝试设置display关键字参数,如:

>>> with mss(display=':0') as sct:
...     sct.shot()