0

This is my first time to create a python program to take screenshot every two seconds. The problem is that I don't know how to break the while loop. I wrote while sscount is not zero, keep screenshotting. Then when a user press ESC button, set sscount to 0. This should stop the while loop but I get the warning, "Unused variable 'sscount'" and it doesn't stop the while loop either.

Could anyone help me? Thanks.

import pynput
import pyautogui
import time

from pynput.keyboard import Key, Listener

count = 0

    def on_release(key):
        if key == Key.esc:
            sscount = 0 #this is where the warning comes.
            return False

    with Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()

    while sscount != 0:
        pyautogui.screenshot('/users/aliha/desktop/screenshot/image'+str(sscount)+'.png')
        sscount += 1
        time.sleep(2.0)
  • You have to use a global variable `sscount`, and declare it as `global` in `on_release` - otherwise each time a new local variable is created and discarded. – MrBean Bremen Apr 14 '20 at 18:30

3 Answers3

1

Below a snippet code to enhance.

  • The main program run while is_running is True
  • ctrl+c event set is_running to False
  • screenshot is took if the elasped time is upper than 2 sec between 2 <escape> key pressed
  • output path is not hardcoded
  • global variable is used to share state
import time
from os.path import expanduser
from pathlib import Path
import datetime
from pynput.keyboard import Key, Listener, Controller


keyboard = Controller()
is_running = True
sscount = 0
previous_date = None
screenshot_dir = None

def on_press(key: Key):
    global previous_date, sscount
    have_to_take_screenshot = False
    current_date = datetime.datetime.now()
    if previous_date is None:
        previous_date = current_date
        have_to_take_screenshot = True
    else:
        elapsed_time = current_date - previous_date
        if elapsed_time > datetime.timedelta(seconds=2):
            previous_date = current_date
            have_to_take_screenshot = True
        else:
            have_to_take_screenshot = False

    print(have_to_take_screenshot)
    if have_to_take_screenshot and key == Key.esc:
        pyautogui.screenshot(f'{screenshot_dir}/image{sscount}.png')
        sscount+= 1


def on_release(key: Key):
    global screenshot_dir
    should_continue = True
    print(key)
    if key == Key.esc:
        is_running = False
        should_continue = False
    return should_continue


if __name__ == '__main__':
    home_dir = expanduser('~/')
    screenshot_dir = Path(f'{home_dir}/desktop/screenshot')

    if not screenshot_dir.exists():
        screenshot_dir.mkdir(parents=True, exist_ok=True)

    while is_running:
        try:
            with Listener(on_press=on_press, on_release=on_release) as listener:
                listener.join()
        except KeyboardInterrupt:
            is_running = False
bioinfornatics
  • 1,749
  • 3
  • 17
  • 36
0

One way to fix this is to raise a StopIteration and make the loop infinite.

import pynput
import pyautogui
import time

from pynput.keyboard import Key, Listener


    def on_release(key):
        if key == Key.esc:
            raise StopIteration

    with Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()

    while True:
        pyautogui.screenshot('/users/aliha/desktop/screenshot/image'+str(sscount)+'.png')
        time.sleep(2.0)
Ahmed Tounsi
  • 1,482
  • 1
  • 14
  • 24
0

In order to be able to use variable sscount globally and to manipulate the global variable within function on_release , you have to declare sscount as global variable in the function using global sscount. Complete result:

def on_release(key):
    global sscount
    if key == Key.esc:
        sscount = 0 #this is where the warning comes.
        return False