How to take a screenshot with Python

This is a small platform-independent python script to take a screenshot of the entire screen. The code is in Python 2.7 and requires the wxPython library which is available in all platforms. By default, it takes an instant screenshot of the screen and saves it as screenshot.png in the same folder as the script. Two command line arguments can be passed as:

  python sshot.py <delay in seconds> <filename to save in>

Delay delays the screenshot by the designated seconds so that you can arrange the screen or windows as required.

The filename argument will save the screenshot in the file <filename>.png . Note that the png suffix is assigned automatically.

 

#
# Take screenshot of screen
# Usage <delay in seconds> <filename>
#
# delay should be a valid number
# filename should not have an extension as it will be saved as a png

# Python 2.7
#

import wx
import time
import sys

time_delay = 0
file_name = "screenshot"

if __name__ == "__main__":
	app = wx.App()
	
	# check for args being passed
	if len(sys.argv) > 1:
		# delay in seconds
		if len(sys.argv) >= 2:
			time_delay = sys.argv[1]
			
			#filename 
			if len(sys.argv) >= 3:
				file_name = sys.argv[2]

	if time_delay > 0:
		time.sleep(float(time_delay))

	# capture screen and save it to file
	screen = wx.ScreenDC()
	size = screen.GetSize()
	bmp = wx.EmptyBitmap(size[0], size[1])
	mem = wx.MemoryDC(bmp)
	mem.Blit(0,0,size[0], size[1], screen, 0, 0)
	del mem
	bmp.SaveFile(file_name + ".png", wx.BITMAP_TYPE_PNG)

	#show alert message
	dlg = wx.MessageDialog(None, "Screenshot was saved as " + file_name + ".png", "Alert", wx.OK | wx.ICON_INFORMATION | wx.STAY_ON_TOP)
	dlg.ShowModal()
	dlg.Destroy()


Be the first to comment

Leave a Reply

Your email address will not be published.


*