问题
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.
Code:
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()
This is the error I'm getting:
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.
回答1:
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")
回答2:
D:/mine\2016-12-02 20:24:37.png. You must have formatted something wrong if it has "/" and "\". And also, same as the other people: you can't create files with colons.
来源:https://stackoverflow.com/questions/40938868/taking-screenshots-with-pil