使用 PIL 截取屏幕截图 [英] Taking screenshots with PIL

查看:155
本文介绍了使用 PIL 截取屏幕截图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写每 1 分钟截屏一次的脚本,但有一个问题,当我保存它时,我的参数无效,我不知道为什么会这样.

I'm working on script that take screenshot every 1 min but there is one problem that when I save it gives me invalid argument and I don't know why that is.

代码:

from PIL import ImageGrab
from PIL import Image
import time
import datetime
import os

def screenShot():
    while True:
        try:
            date = str(datetime.date.today())
            hour=str(datetime.datetime.now().strftime("%H"))
            os.makedirs("D:/mine/" + date + "/" + hour)
        except OSError,e:
            if e.errno != 17:
                raise
            time.sleep(1)
            pass
        while True:
            date = str(datetime.date.today())
            hour = str(datetime.datetime.now().strftime("%H"))
            date_time = str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
            img = ImageGrab.grab()
            FILES_DIR = 'mine'
            SAVE_PATH = "D:/"
            LOGFILE_NAME = "%s.png" % date_time
            LOGFILE_PATH = os.path.join(SAVE_PATH, FILES_DIR, LOGFILE_NAME)
            img.save(LOGFILE_PATH)
            break
        time.sleep(60)

screenShot()

这是我得到的错误:

IOError: [Erno 22] Invalid argument: 'D:/mine\\2016-12-02 20:24:37.png'

我搜索了很多,我找到了这段代码并且它有效,但我看不出这段代码和我的代码有什么不同.

I searched a lot and I found this code and it worked but I can't see different between this code and my code.

import os
import sys
import time
from PIL import ImageGrab
from PIL import Image
from os import environ
import random
n = -1
while True:
    n += 1
    # generate a random time between 120 and 300 sec
    random_time = random.randrange(1,2)
    # 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)
    img = ImageGrab.grab()
    FILES_DIR = 'mine'
    SAVE_PATH = "D:/"
    #SAVE_PATH = os.path.expanduser("~")    #It is cross-platform
    LOGFILE_NAME = "test{n:0>5}.png".format(n = n)
    LOGFILE_PATH = os.path.join(SAVE_PATH, FILES_DIR, LOGFILE_NAME)
    print LOGFILE_PATH
    img.save(LOGFILE_PATH)

我忘记了一些东西,但我不知道是什么.

I'm forgetting something but I don't know what is it.

推荐答案

确保 SAVE_PATHFILES_DIR 是有效的,这意味着它们存在于您的硬盘驱动器中,并且路径应该是绝对路径.例如在 linux 中它应该是 ~/D/mine 在你的情况下它应该是 D:\mine 而不是 D:/minestrftime("%Y-%m-%d %H:%M:%S") 应该是 strftime("%Y-%m-%d %H.%M.%S")

Make sure the SAVE_PATH and FILES_DIR are valid meaning they exist in your hard drive and the path should be absolute path. for example in linux it would be ~/D/mine in your case it should be D:\mine instead of D:/mine also strftime("%Y-%m-%d %H:%M:%S") should be strftime("%Y-%m-%d %H.%M.%S")

这篇关于使用 PIL 截取屏幕截图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆