使用 Python 随机间隔截取屏幕截图?

使用 Python 随机间隔截取屏幕截图?

我正在开发一个项目,用于截取桌面屏幕截图并将图片上传到服务器。我想开发一个 Python 应用程序,当用户启动该应用程序时,它会在随机间隔内开始截取屏幕截图,间隔为 2-5 分钟。我有截取屏幕截图的代码,我已经在 ubuntu 上测试过了,运行正常。截取屏幕截图的代码

import gtk.gdk
import 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.time()
filename = "screenshot"
filename += str(ts)
filename += ".png"

if (pb != None):
    pb.save(filename,"png")
    print "Screenshot saved to "+filename
else:
    print "Unable to get the screenshot."

我想以 2-5 分钟的随机间隔运行此代码,如何开发在线程中运行此代码的脚本。

答案1

#!/usr/bin/env python

import gtk.gdk
import time
import random

while 1 :
    # generate a random time between 120 and 300 sec
    random_time = random.randrange(120,300)

    # 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.time()
    filename = "screenshot"
    filename += str(ts)
    filename += ".png"

    if (pb != None):
        pb.save(filename,"png")
        print "Screenshot saved to "+filename
    else:
        print "Unable to get the screenshot."

答案2

我很想把它外包给一个外部库,比如Py截图

让它处理繁重的工作(比如确定它需要哪个 DM 和屏幕 API),然后给你留下一个 PIL 图像,你可以将其保存到磁盘或作为上传流式传输出去。

有很多答案在 Stack Overflow 上手动执行此操作但是,如果你决心自己动手的话。


至于间隔,这必须是线程化的吗?脚本不能单独运行,然后在拍摄快照后随机休眠一段时间(120 到 300 秒之间)吗?

import random
import time

time.sleep(random.randrange(120, 300))

相关内容