Take a screenshot via a Python script on Linux

后端 未结 15 1162
暖寄归人
暖寄归人 2020-11-22 11:50

I want to take a screenshot via a python script and unobtrusively save it.

I\'m only interested in the Linux solution, and should support any X based environment.

15条回答
  •  醉梦人生
    2020-11-22 12:31

    Try it:

    #!/usr/bin/python
    
    import gtk.gdk
    import time
    import random
    import socket
    import fcntl
    import struct
    import getpass
    import os
    import paramiko     
    
    while 1:
        # generate a random time between 120 and 300 sec
        random_time = random.randrange(20,25)
        # wait between 120 and 300 seconds (or between 2 and 5 minutes) 
    
        print "Next picture in: %.2f minutes" % (float(random_time) / 60)
    
        time.sleep(random_time)
        w = gtk.gdk.get_default_root_window()   
        sz = w.get_size()
        print "The size of the window is %d x %d" % sz
        pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
        pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
        ts = time.asctime( time.localtime(time.time()) )
        date = time.strftime("%d-%m-%Y")
        timer = time.strftime("%I:%M:%S%p")
        filename = timer
        filename += ".png"
    
        if (pb != None):
            username = getpass.getuser() #Get username
            newpath = r'screenshots/'+username+'/'+date #screenshot save path
            if not os.path.exists(newpath): os.makedirs(newpath)
            saveas = os.path.join(newpath,filename)
            print saveas
            pb.save(saveas,"png")
        else:
            print "Unable to get the screenshot."
    

提交回复
热议问题