简体   繁体   中英

Python Screen capture

I'm trying to write a program to take screen cap using a global hot key. Below is the corresponding code:

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

Error Message:

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: ''

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

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:
 

I do not know how to save the image to the folder. I expect the code below will not work this:

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

Changing the function to on_activate with a simple action such as:

Print("Hello")

The hotkey script works perfectly.

I am new to programming, so any help is appreciated!

Here the fixed code:

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

The problem was that you were using:

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

The function pathlib.Path(fpath,d,".jpg") join the string adding the \\ to the end of each, so the path where you are trying to save the file is:

C:Users\\Desktop\\TestScreenCap\\200309\\2020-09-03-16-50-20\\.jpg

As you can see the filename is the extension, that throw the exception.

Just replace with this: myScreenshot.save(pathlib.Path(fpath,d + ".jpg"))

Another problem on the specified path is that C: is interpreted as Drive, so when you save the function, is saved to the path where your program is currently running, not at the real specified path. To fix this part, just replace C: with C:\\\\ .

Reading your code I think you would like to save the screenshot in the current user Desktop, if so replace the line: fpath = pathlib.Path("C:\\\\","Users","Desktop","TestScreenCap", time_stamp) with fpath = pathlib.Path(os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop'), time_stamp) and just add on the top the import os . With this you don't need to care about the right generation for the path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM