1 回答
TA贡献1911条经验 获得超7个赞
这里是固定代码:
from datetime import datetime
import os
from pynput import keyboard
import pyautogui
import pathlib
def on_activate():
today = datetime.now()
d = today.strftime("%Y-%m-%d-%H-%M-%S")
myScreenshot = pyautogui.screenshot(region=(200,200, 1720, 800))
time_stamp = '{:%y%d%m}'.format(today)
fpath = pathlib.Path("C:\\","Users","Desktop","TestScreenCap", time_stamp)
if not os.path.exists(fpath):
os.makedirs(fpath)
myScreenshot.save(pathlib.Path(fpath,d + ".jpg"))
def for_canonical(f):
return lambda k: f(l.canonical(k))
hotkey = keyboard.HotKey(
keyboard.HotKey.parse('<ctrl>+<alt>+h'),
on_activate)
with keyboard.Listener(
on_press=for_canonical(hotkey.press),
on_release=for_canonical(hotkey.release)) as l:
l.join()
问题是您正在使用:
myScreenshot.save(pathlib.Path(fpath,d,".jpg"))
该函数pathlib.Path(fpath,d,".jpg")将字符串添加\到每个字符串的末尾,因此您尝试保存文件的路径是:
C:Users\Desktop\TestScreenCap\200309\2020-09-03-16-50-20\.jpg
正如您所看到的,文件名是引发异常的扩展名。
只需替换为:myScreenshot.save(pathlib.Path(fpath,d + ".jpg"))
指定路径的另一个问题是它C:被解释为Drive,所以当你保存函数时,保存到你的程序当前运行的路径,而不是真正的指定路径。要修复此部分,只需替换C:为C:\\.
阅读您的代码,我认为您希望将屏幕截图保存在当前用户桌面中,如果是这样,请将行:替换为fpath = pathlib.Path("C:\\","Users","Desktop","TestScreenCap", time_stamp)并fpath = pathlib.Path(os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop'), time_stamp)在顶部添加import os. 有了这个,你就不需要关心这条道路的正确世代。
添加回答
举报