3131
3232
3333from struct import pack
34+ from os .path import isfile
3435from platform import system
3536import sys
3637import zlib
@@ -45,7 +46,7 @@ class ScreenshotError(Exception):
4546 from LaunchServices import kUTTypePNG
4647elif system () == 'Linux' :
4748 from os import environ
48- from os .path import expanduser , isfile
49+ from os .path import expanduser
4950 import xml .etree .ElementTree as ET
5051 from ctypes .util import find_library
5152 from ctypes import byref , cast , cdll , POINTER , Structure , \
@@ -202,14 +203,19 @@ def get_pixels(self, monitor_infos):
202203 '''
203204 return NotImplemented
204205
205- def save (self , output = 'screenshot' , screen = 0 ):
206+ def save (self , output = 'screenshot' , screen = 0 , callback = lambda * x : True ):
206207 ''' For each monitor, grab a screen shot and save it to a file.
207208
208209 Parameters:
209210 - output - string - the output filename without extension
210211 - screen - int - grab one screen shot of all monitors (screen=-1)
211212 grab one screen shot by monitor (screen=0)
212213 grab the screen shot of the monitor N (screen=N)
214+ - callback - function - in case where output already exists, call
215+ the defined callback function with output
216+ as parameter. If it returns True, then
217+ continue; else ignores the monitor and
218+ switches to ne next.
213219
214220 This is a generator which returns created files:
215221 'screenshot-1.png',
@@ -235,6 +241,8 @@ def save(self, output='screenshot', screen=0):
235241 filename = '{}.png' .format (output )
236242
237243 if screen <= 0 or (screen > 0 and i + 1 == screen ):
244+ if isfile (filename ) and not callback (filename ):
245+ continue
238246 self .debug ('save' , 'filename' , filename )
239247 self .save_img (data = self .get_pixels (monitor ),
240248 width = monitor [b'width' ],
@@ -763,6 +771,21 @@ def timer(msg):
763771 with timer ('All in one ' ):
764772 for filename in mss .save (screen = - 1 ):
765773 print (' File: {}' .format (filename ))
774+
775+ # Example with a callback
776+ def on_exists (fname ):
777+ ''' Callback example when we try to overwrite an existing screen shot. '''
778+
779+ from os import rename
780+ newfile = fname + '.old'
781+ print (' Renaming {} to {}' .format (fname , newfile ))
782+ rename (fname , newfile )
783+ return True
784+
785+ # Screen shot of the monitor 1, with callback
786+ with timer ('Monitor 1 ' ):
787+ for filename in mss .save (output = 'monitor-1' , screen = 1 , callback = on_exists ):
788+ print (' File: {}' .format (filename ))
766789 return 0
767790
768791
0 commit comments