<p>I want to take a screenshot via a python script and unobtrusively save it.</p>

<p>I'm only interested in the Linux solution, and should support any X based environment.</p>

[{'answer_id': 70237, 'author': 'Slava V', 'author_id': 37141, 'author_profile': 'https://Stackoverflow.com/users/37141', 'pm_score': 3, 'selected': False, 'text': "<pre><code>import ImageGrab\nimg = ImageGrab.grab()\nimg.save('test.jpg','JPEG')\n</code></pre>\n\n<p>this requires Python Imaging Library</p>\n"}, {'answer_id': 769221, 'author': 'Juliano', 'author_id': 55078, 'author_profile': 'https://Stackoverflow.com/users/55078', 'pm_score': 4, 'selected': False, 'text': '<p>This one works on X11, and perhaps on Windows too (someone, please check). Needs <a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro" rel="noreferrer">PyQt4</a>:</p>\n\n<pre><code>import sys\nfrom PyQt4.QtGui import QPixmap, QApplication\napp = QApplication(sys.argv)\nQPixmap.grabWindow(QApplication.desktop().winId()).save(\'test.png\', \'png\')\n</code></pre>\n'}, {'answer_id': 782768, 'author': 'Rusty', 'author_id': 95083, 'author_profile': 'https://Stackoverflow.com/users/95083', 'pm_score': 7, 'selected': True, 'text': '<p>This works without having to use scrot or ImageMagick.</p>\n\n<pre><code>import gtk.gdk\n\nw = gtk.gdk.get_default_root_window()\nsz = w.get_size()\nprint "The size of the window is %d x %d" % sz\npb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])\npb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])\nif (pb != None):\n    pb.save("screenshot.png","png")\n    print "Screenshot saved to screenshot.png."\nelse:\n    print "Unable to get the screenshot."\n</code></pre>\n\n<p>Borrowed from <a href="http://ubuntuforums.org/showpost.php?p=2681009&amp;postcount=5" rel="noreferrer">http://ubuntuforums.org/showpost.php?p=2681009&amp;postcount=5</a></p>\n'}, {'answer_id': 6380186, 'author': 'Snowball', 'author_id': 802490, 'author_profile': 'https://Stackoverflow.com/users/802490', 'pm_score': 3, 'selected': False, 'text': '<p>Cross platform solution using <a href="http://wxpython.org" rel="noreferrer">wxPython</a>:</p>\n\n<pre><code>import wx\nwx.App()  # Need to create an App instance before doing anything\nscreen = wx.ScreenDC()\nsize = screen.GetSize()\nbmp = wx.EmptyBitmap(size[0], size[1])\nmem = wx.MemoryDC(bmp)\nmem.Blit(0, 0, size[0], size[1], screen, 0, 0)\ndel mem  # Release bitmap\nbmp.SaveFile(\'screenshot.png\', wx.BITMAP_TYPE_PNG)\n</code></pre>\n'}, {'answer_id': 7711106, 'author': 'Alex Raeder', 'author_id': 244382, 'author_profile': 'https://Stackoverflow.com/users/244382', 'pm_score': 6, 'selected': False, 'text': '<p>Compile all answers in one class.\nOutputs PIL image.</p>\n\n<pre><code>#!/usr/bin/env python\n# encoding: utf-8\n"""\nscreengrab.py\n\nCreated by Alex Snet on 2011-10-10.\nCopyright (c) 2011 CodeTeam. All rights reserved.\n"""\n\nimport sys\nimport os\n\nimport Image\n\n\nclass screengrab:\n    def __init__(self):\n        try:\n            import gtk\n        except ImportError:\n            pass\n        else:\n            self.screen = self.getScreenByGtk\n\n        try:\n            import PyQt4\n        except ImportError:\n            pass\n        else:\n            self.screen = self.getScreenByQt\n\n        try:\n            import wx\n        except ImportError:\n            pass\n        else:\n            self.screen = self.getScreenByWx\n\n        try:\n            import ImageGrab\n        except ImportError:\n            pass\n        else:\n            self.screen = self.getScreenByPIL\n\n\n    def getScreenByGtk(self):\n        import gtk.gdk      \n        w = gtk.gdk.get_default_root_window()\n        sz = w.get_size()\n        pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])\n        pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])\n        if pb is None:\n            return False\n        else:\n            width,height = pb.get_width(),pb.get_height()\n            return Image.fromstring("RGB",(width,height),pb.get_pixels() )\n\n    def getScreenByQt(self):\n        from PyQt4.QtGui import QPixmap, QApplication\n        from PyQt4.Qt import QBuffer, QIODevice\n        import StringIO\n        app = QApplication(sys.argv)\n        buffer = QBuffer()\n        buffer.open(QIODevice.ReadWrite)\n        QPixmap.grabWindow(QApplication.desktop().winId()).save(buffer, \'png\')\n        strio = StringIO.StringIO()\n        strio.write(buffer.data())\n        buffer.close()\n        del app\n        strio.seek(0)\n        return Image.open(strio)\n\n    def getScreenByPIL(self):\n        import ImageGrab\n        img = ImageGrab.grab()\n        return img\n\n    def getScreenByWx(self):\n        import wx\n        wx.App()  # Need to create an App instance before doing anything\n        screen = wx.ScreenDC()\n        size = screen.GetSize()\n        bmp = wx.EmptyBitmap(size[0], size[1])\n        mem = wx.MemoryDC(bmp)\n        mem.Blit(0, 0, size[0], size[1], screen, 0, 0)\n        del mem  # Release bitmap\n        #bmp.SaveFile(\'screenshot.png\', wx.BITMAP_TYPE_PNG)\n        myWxImage = wx.ImageFromBitmap( myBitmap )\n        PilImage = Image.new( \'RGB\', (myWxImage.GetWidth(), myWxImage.GetHeight()) )\n        PilImage.fromstring( myWxImage.GetData() )\n        return PilImage\n\nif __name__ == \'__main__\':\n    s = screengrab()\n    screen = s.screen()\n    screen.show()\n</code></pre>\n'}, {'answer_id': 7817506, 'author': 'ponty', 'author_id': 700820, 'author_profile': 'https://Stackoverflow.com/users/700820', 'pm_score': 4, 'selected': False, 'text': '<p>I have a wrapper project (<a href="https://github.com/ponty/pyscreenshot" rel="noreferrer">pyscreenshot</a>) for scrot, imagemagick, pyqt, wx and pygtk.\nIf you have one of them, you can use it.\nAll solutions are included from this discussion.</p>\n\n<p>Install:</p>\n\n<pre><code>easy_install pyscreenshot\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>import pyscreenshot as ImageGrab\n\n# fullscreen\nim=ImageGrab.grab()\nim.show()\n\n# part of the screen\nim=ImageGrab.grab(bbox=(10,10,500,500))\nim.show()\n\n# to file\nImageGrab.grab_to_file(\'im.png\')\n</code></pre>\n'}, {'answer_id': 16141058, 'author': 'b0bz', 'author_id': 1149259, 'author_profile': 'https://Stackoverflow.com/users/1149259', 'pm_score': 6, 'selected': False, 'text': "<p>Just for completeness:\nXlib - But it's somewhat slow when capturing the whole screen:</p>\n<pre><code>from Xlib import display, X\nimport Image #PIL\n\nW,H = 200,200\ndsp = display.Display()\ntry:\n    root = dsp.screen().root\n    raw = root.get_image(0, 0, W,H, X.ZPixmap, 0xffffffff)\n    image = Image.fromstring(&quot;RGB&quot;, (W, H), raw.data, &quot;raw&quot;, &quot;BGRX&quot;)\n    image.show()\nfinally:\n    dsp.close()\n</code></pre>\n<p>One could try to trow some types in the bottleneck-files in PyXlib, and then compile it using Cython. That could increase the speed a bit.</p>\n<hr />\n<p><strong>Edit:</strong>\nWe can write the core of the function in C, and then use it in python from ctypes, here is something I hacked together:</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;X11/X.h&gt;\n#include &lt;X11/Xlib.h&gt;\n//Compile hint: gcc -shared -O3 -lX11 -fPIC -Wl,-soname,prtscn -o prtscn.so prtscn.c\n\nvoid getScreen(const int, const int, const int, const int, unsigned char *);\nvoid getScreen(const int xx,const int yy,const int W, const int H, /*out*/ unsigned char * data) \n{\n   Display *display = XOpenDisplay(NULL);\n   Window root = DefaultRootWindow(display);\n\n   XImage *image = XGetImage(display,root, xx,yy, W,H, AllPlanes, ZPixmap);\n\n   unsigned long red_mask   = image-&gt;red_mask;\n   unsigned long green_mask = image-&gt;green_mask;\n   unsigned long blue_mask  = image-&gt;blue_mask;\n   int x, y;\n   int ii = 0;\n   for (y = 0; y &lt; H; y++) {\n       for (x = 0; x &lt; W; x++) {\n         unsigned long pixel = XGetPixel(image,x,y);\n         unsigned char blue  = (pixel &amp; blue_mask);\n         unsigned char green = (pixel &amp; green_mask) &gt;&gt; 8;\n         unsigned char red   = (pixel &amp; red_mask) &gt;&gt; 16;\n\n         data[ii + 2] = blue;\n         data[ii + 1] = green;\n         data[ii + 0] = red;\n         ii += 3;\n      }\n   }\n   XDestroyImage(image);\n   XDestroyWindow(display, root);\n   XCloseDisplay(display);\n}\n</code></pre>\n<p>And then the python-file:</p>\n<pre><code>import ctypes\nimport os\nfrom PIL import Image\n\nLibName = 'prtscn.so'\nAbsLibPath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + LibName\ngrab = ctypes.CDLL(AbsLibPath)\n\ndef grab_screen(x1,y1,x2,y2):\n    w, h = x2-x1, y2-y1\n    size = w * h\n    objlength = size * 3\n\n    grab.getScreen.argtypes = []\n    result = (ctypes.c_ubyte*objlength)()\n\n    grab.getScreen(x1,y1, w, h, result)\n    return Image.frombuffer('RGB', (w, h), result, 'raw', 'RGB', 0, 1)\n    \nif __name__ == '__main__':\n  im = grab_screen(0,0,1440,900)\n  im.show()\n</code></pre>\n"}, {'answer_id': 20219666, 'author': 'Anand', 'author_id': 2659276, 'author_profile': 'https://Stackoverflow.com/users/2659276', 'pm_score': -1, 'selected': False, 'text': '<p>Try it:</p>\n\n<pre><code>#!/usr/bin/python\n\nimport gtk.gdk\nimport time\nimport random\nimport socket\nimport fcntl\nimport struct\nimport getpass\nimport os\nimport paramiko     \n\nwhile 1:\n    # generate a random time between 120 and 300 sec\n    random_time = random.randrange(20,25)\n    # wait between 120 and 300 seconds (or between 2 and 5 minutes) \n\n    print "Next picture in: %.2f minutes" % (float(random_time) / 60)\n\n    time.sleep(random_time)\n    w = gtk.gdk.get_default_root_window()   \n    sz = w.get_size()\n    print "The size of the window is %d x %d" % sz\n    pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])\n    pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])\n    ts = time.asctime( time.localtime(time.time()) )\n    date = time.strftime("%d-%m-%Y")\n    timer = time.strftime("%I:%M:%S%p")\n    filename = timer\n    filename += ".png"\n\n    if (pb != None):\n        username = getpass.getuser() #Get username\n        newpath = r\'screenshots/\'+username+\'/\'+date #screenshot save path\n        if not os.path.exists(newpath): os.makedirs(newpath)\n        saveas = os.path.join(newpath,filename)\n        print saveas\n        pb.save(saveas,"png")\n    else:\n        print "Unable to get the screenshot."\n</code></pre>\n'}, {'answer_id': 23609424, 'author': 'ouille', 'author_id': 2761803, 'author_profile': 'https://Stackoverflow.com/users/2761803', 'pm_score': 2, 'selected': False, 'text': '<p>There is a python package for this <a href="http://www.autopy.org/" rel="nofollow">Autopy</a></p>\n\n<p>The bitmap module can to screen grabbing (bitmap.capture_screen)\nIt is multiplateform (Windows, Linux, Osx).</p>\n'}, {'answer_id': 25805492, 'author': 'rominf', 'author_id': 2108548, 'author_profile': 'https://Stackoverflow.com/users/2108548', 'pm_score': 0, 'selected': False, 'text': "<p>It's an old question. I would like to answer it using new tools.</p>\n\n<p>Works with python 3 (should work with python 2, but I haven't test it) and PyQt5.</p>\n\n<p>Minimal working example. Copy it to the python shell and get the result.</p>\n\n<pre><code>from PyQt5.QtWidgets import QApplication\napp = QApplication([])\nscreen = app.primaryScreen()\nscreenshot = screen.grabWindow(QApplication.desktop().winId())\nscreenshot.save('/tmp/screenshot.png')\n</code></pre>\n"}, {'answer_id': 29136548, 'author': 'anderstood', 'author_id': 1555099, 'author_profile': 'https://Stackoverflow.com/users/1555099', 'pm_score': 1, 'selected': False, 'text': '<p>From <a href="http://ubuntuforums.org/showthread.php?t=448160" rel="nofollow">this thread</a>:</p>\n\n<pre><code> import os\n os.system("import -window root temp.png")\n</code></pre>\n'}, {'answer_id': 30503686, 'author': 'pkm', 'author_id': 2490439, 'author_profile': 'https://Stackoverflow.com/users/2490439', 'pm_score': 2, 'selected': False, 'text': '<p>bit late but nevermind easy one is</p>\n\n<pre><code>import autopy\nimport time\ntime.sleep(2)\nb = autopy.bitmap.capture_screen()\nb.save("C:/Users/mak/Desktop/m.png")\n</code></pre>\n'}, {'answer_id': 45579657, 'author': 'cyera', 'author_id': 8436827, 'author_profile': 'https://Stackoverflow.com/users/8436827', 'pm_score': 2, 'selected': False, 'text': '<p>I couldn\'t take screenshot in Linux with pyscreenshot or scrot because output of <code>pyscreenshot</code> was just a black screen png image file.</p>\n\n<p>but thank god there was another very easy way for taking screenshot in Linux without installing anything. just put below code in your directory and run with <code>python demo.py</code></p>\n\n<pre><code>import os\nos.system("gnome-screenshot --file=this_directory.png")\n</code></pre>\n\n<p>also there is many available options for <code>gnome-screenshot --help</code></p>\n\n<pre><code>Application Options:\n  -c, --clipboard                Send the grab directly to the clipboard\n  -w, --window                   Grab a window instead of the entire screen\n  -a, --area                     Grab an area of the screen instead of the entire screen\n  -b, --include-border           Include the window border with the screenshot\n  -B, --remove-border            Remove the window border from the screenshot\n  -p, --include-pointer          Include the pointer with the screenshot\n  -d, --delay=seconds            Take screenshot after specified delay [in seconds]\n  -e, --border-effect=effect     Effect to add to the border (shadow, border, vintage or none)\n  -i, --interactive              Interactively set options\n  -f, --file=filename            Save screenshot directly to this file\n  --version                      Print version information and exit\n  --display=DISPLAY              X display to use\n</code></pre>\n'}, {'answer_id': 52549704, 'author': 'Jack Sparrow', 'author_id': 3293019, 'author_profile': 'https://Stackoverflow.com/users/3293019', 'pm_score': 3, 'selected': False, 'text': '<p>You can use this</p>\n\n<pre><code>import os\nos.system("import -window root screen_shot.png")\n</code></pre>\n'}, {'answer_id': 64236518, 'author': 'Matheus K.', 'author_id': 14391919, 'author_profile': 'https://Stackoverflow.com/users/14391919', 'pm_score': 2, 'selected': False, 'text': "<p>for ubuntu this work for me, you can take a screenshot of select window with this:</p>\n<pre><code>import gi\ngi.require_version('Gtk', '3.0')\ngi.require_version('Gdk', '3.0')\n\nfrom gi.repository import Gdk\nfrom gi.repository import GdkPixbuf\nimport numpy as np\nfrom Xlib.display import Display\n\n#define the window name\nwindow_name = 'Spotify'\n\n#define xid of your select 'window'\ndef locate_window(stack,window):\n    disp = Display()\n    NET_WM_NAME = disp.intern_atom('_NET_WM_NAME')\n    WM_NAME = disp.intern_atom('WM_NAME') \n    name= []\n    for i, w in enumerate(stack):\n        win_id =w.get_xid()\n        window_obj = disp.create_resource_object('window', win_id)\n        for atom in (NET_WM_NAME, WM_NAME):\n            window_name=window_obj.get_full_property(atom, 0)\n            name.append(window_name.value)\n    for l in range(len(stack)):\n        if(name[2*l]==window):\n            return stack[l]\n\nwindow = Gdk.get_default_root_window()\nscreen = window.get_screen()\nstack = screen.get_window_stack()\nmyselectwindow = locate_window(stack,window_name)\nimg_pixbuf = Gdk.pixbuf_get_from_window(myselectwindow,*myselectwindow.get_geometry()) \n</code></pre>\n<p>to transform pixbuf into array</p>\n<pre><code>def pixbuf_to_array(p):\n    w,h,c,r=(p.get_width(), p.get_height(), p.get_n_channels(), p.get_rowstride())\n    assert p.get_colorspace() == GdkPixbuf.Colorspace.RGB\n    assert p.get_bits_per_sample() == 8\n    if  p.get_has_alpha():\n        assert c == 4\n    else:\n        assert c == 3\n    assert r &gt;= w * c\n    a=np.frombuffer(p.get_pixels(),dtype=np.uint8)\n    if a.shape[0] == w*c*h:\n        return a.reshape( (h, w, c) )\n    else:\n        b=np.zeros((h,w*c),'uint8')\n        for j in range(h):\n            b[j,:]=a[r*j:r*j+w*c]\n        return b.reshape( (h, w, c) )\n\nbeauty_print = pixbuf_to_array(img_pixbuf)\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/69645', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1724701/']