Search code examples
pythonscreenshot

How to take a screenshot in Python?


I'm trying to take a screenshot using python that would work on both Windows and Linux. I've read pyscreenshot could do the job. But I have an error and the documentation doesn't seem to specify any dependency.

import pyscreenshot as ImageGrab
im = ImageGrab.grab()
im.show()

Traceback:

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/pyscreenshot/procutil.py", line 15, in _wrapper
    r = target(*args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/pyscreenshot/__init__.py", line 33, in _grab_simple
    return backend_obj.grab(bbox)
  File "/usr/local/lib/python3.6/dist-packages/pyscreenshot/plugins/wxscreen.py", line 39, in grab
    im.frombytes(buffer(myWxImage.GetData()))
NameError: name 'buffer' is not defined

Traceback (most recent call last):
  File "ambi.py", line 10, in <module>
    im = ImageGrab.grab()
  File "/usr/local/lib/python3.6/dist-packages/pyscreenshot/__init__.py", line 67, in grab
    to_file=False, childprocess=childprocess, backend=backend, bbox=bbox)
  File "/usr/local/lib/python3.6/dist-packages/pyscreenshot/__init__.py", line 46, in _grab
    _grab_simple, imcodec.codec, to_file, backend, bbox, filename)
  File "/usr/local/lib/python3.6/dist-packages/pyscreenshot/procutil.py", line 37, in run_in_childprocess
    raise e
NameError: name 'buffer' is not defined

I installed it with sudo pip3 install pyscreenshot

I tried installing wxscreen, but it doesn't seem to find a package with that name.

I don't want to use libraries that mimic keyboard inputs as the script will run in the background while playing games to monitor stats. Anti-Cheats could get triggered.


Solution

  • Another approach that is really fast is the MSS module. It is different from other solutions in the way that it uses only the ctypes standard module, so it does not require big dependencies. It is OS independant and its use is made easy:

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

    And just find the screenshot.png file containing the screen shot of the first monitor. There are a lot of possibile customizations, you can play with ScreenShot objects and OpenCV/Numpy/PIL/etc..