简体   繁体   English

Python 中未使用的变量

[英]Unused variable in Python

This is my first time to create a python program to take screenshot every two seconds.这是我第一次创建一个 python 程序来每两秒截图一次。 The problem is that I don't know how to break the while loop.问题是我不知道如何打破 while 循环。 I wrote while sscount is not zero, keep screenshotting.我写的时候 sscount 不为零,继续截图。 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.然后,当用户按下 ESC 按钮时,将 sscount 设置为 0。这应该会停止 while 循环,但我收到警告“Unused variable 'sscount'”并且它也不会停止 while 循环。

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)

Below a snippet code to enhance.下面是一段代码来增强。

  • The main program run while is_running is True主程序在is_runningTrue时运行
  • ctrl+c event set is_running to False ctrl+c事件设置is_runningFalse
  • screenshot is took if the elasped time is upper than 2 sec between 2 <escape> key pressed如果在按下 2 个<escape>键之间的时间超过 2 秒,则会截取屏幕截图
  • output path is not hardcoded output 路径未硬编码
  • global variable is used to share state全局变量用于共享 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

One way to fix this is to raise a StopIteration and make the loop infinite.解决此问题的一种方法是引发StopIteration并使循环无限。

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)

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 .为了能够全局使用变量sscount并在 function on_release中操作全局变量,您必须使用global sscount在 function 中将 sscount 声明为全局变量。 Complete result:完整结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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