Python屏幕截图

时间:2020-09-03 14:18:36

标签: python pyautogui

我正在尝试编写一个使用全局热键进行屏幕捕捉的程序。下面是相应的代码:

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()

错误消息:

Unhandled exception in listener callback
Traceback (most recent call last):
  File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\PIL\Image.py", line 2138, in save format = EXTENSION[ext]
KeyError: ''

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\_util\__init__.py", line 211, in inner
    return f(self, *args, **kwargs)
  File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\keyboard\_win32.py", line 280, in _process self.on_press(key)
  File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\_util\__init__.py", line 127, in inner
    if f(*args) is False:
  File "C:/Users/PycharmProjects/untitled1/123.py", line 18, in <lambda>
    return lambda k: f(l.canonical(k))
  File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\keyboard\__init__.py", line 182, in press
    self._on_activate()
  File "C:/Users/PycharmProjects/untitled1/123.py", line 15, in on_activate
    myScreenshot.save(pathlib.Path(fpath,d,".jpg"))
  File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\PIL\Image.py", line 2140, in save
    raise ValueError("unknown file extension: {}".format(ext)) from e
ValueError: unknown file extension: 
Traceback (most recent call last):
  File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\PIL\Image.py", line 2138, in save
    format = EXTENSION[ext]
KeyError: ''

上述异常是以下异常的直接原因:

Traceback (most recent call last):
  File "C:/Users/PycharmProjects/untitled1/123.py", line 26, in <module>
    l.join()

  File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\_util\__init__.py", line 259, in join
    six.reraise(exc_type, exc_value, exc_traceback)

  File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\six.py", line 702, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\_util\__init__.py", line 211, in inner
    return f(self, *args, **kwargs)
  File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\keyboard\_win32.py", line 280, in _process
    self.on_press(key)
  File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\_util\__init__.py", line 127, in inner
    if f(*args) is False:
  File "C:/Users/PycharmProjects/untitled1/123.py", line 18, in <lambda>
    return lambda k: f(l.canonical(k))
  File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\keyboard\__init__.py", line 182, in press
    self._on_activate()
  File "C:/Users/PycharmProjects/untitled1/123.py", line 15, in on_activate
    myScreenshot.save(pathlib.Path(fpath,d,".jpg"))
  File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\PIL\Image.py", line 2140, in save
    raise ValueError("unknown file extension: {}".format(ext)) from e
ValueError: unknown file extension:
 

我不知道如何将图像保存到文件夹。我希望下面的代码行不通:

myScreenshot.save(pathlib.Path(fpath,d,".jpg"))

通过简单的操作将函数更改为on_activate

Print("Hello")

热键脚本运行完美。

我是编程的新手,所以我们将不胜感激!

1 个答案:

答案 0 :(得分:1)

这里是固定代码:

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 。这样,您就不必关心路径的正确生成。