微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

不知道如何在 else 命令之后执行函数

如何解决不知道如何在 else 命令之后执行函数

我正在尝试通过网络摄像头拍摄图像,然后通过 gmail 发送图像。如果系统知道我的指纹,该功能就会发生。如果是,则需要执行发送电子邮件功能。我在发送电子邮件功能之后添加了将“HIGH”发送到 gpio。我不认为它会干扰。

当有一个已知模板时,它后面跟着一个“else:”语句。然后我把我的“def find_newest_file(dir):”函数。我究竟做错了什么? 可能会注意到我在编程方面很糟糕。谢谢!

Pyfingerprint

import os
import glob
import time
import smtplib
import imghdr
from email.message import EmailMessage
import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BCM)
GPIO.setup(26,GPIO.OUT)
import hashlib
from pyfingerprint.pyfingerprint import PyFingerprint

GPIO.output(26,0)
## Search for a finger
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0',57600,0xFFFFFFFF,0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor Could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))

## Tries to search the finger and calculate hash
try:
    print('Waiting for finger...')

    ## Wait that finger is read
    while ( f.readImage() == False ):
        pass

    ## Converts read image to characteristics and stores it in charbuffer 1
    f.convertimage(0x01)

    ## Searchs template
    result = f.searchTemplate()

    positionNumber = result[0]
    accuracyscore = result[1]

    if ( positionNumber == -1 ):
        print('No match found!')
        exit(0)
    else:
        print('Found template at position #' + str(positionNumber))
        print('The accuracy score is: ' + str(accuracyscore))

             def find_newest_file(dir):
                 os.system('fswebcam -r 1280x720 -S 3 --jpeg 90 --save /home/pi/Pictures/%H%M%s.jpg')
                 types = ['*.png','*.jpg'] 
                 files = []
                 if not os.path.isdir(dir):
                     print(f'ERROR: {dir} does not exist. or it is not a valid folder')
                     exit()
            for ext in types:
                scan_path = os.path.abspath(os.path.join(dir,ext))
                files.extend(glob.glob(scan_path))
       
            if len(files) == 0:
                print(f'ERROR: file not found  while scanning folder: {dir} for: {types}')
                exit()
        
            newest = None
            n_time = 0
            for file in files:
        # print(file)
            c_time = os.path.getctime(file)
            if c_time > n_time:
                n_time = c_time
                newest = file
    
           if newest is None:
               print(f'-----------\nUnexpected error: None was return while the list was not empty:\n{files}')
               exit()
        
           if os.path.exists(newest):
               return newest  # return as a list since this is what Yehonata expect
           else:
               print(f'ERROR: File {newest} not found')
               exit()

# Yehontan Code
        Sender_Email = "Sender@gmail.com"
        Reciever_Email = "reciver@gmailcom"
        Password = input('Enter your email account password: ')

        newMessage = EmailMessage()
        newMessage['Subject'] = "Check out the new logo" 
        newMessage['From'] = Sender_Email
        newMessage['To'] = Reciever_Email
        newMessage.set_content('Let me kNow what you think. Image attached!')

# Tomerl: Replace static name with seach function
        files = [ find_newest_file('/home/pi/Pictures/') ]

        for file in files:
            with open(file,'rb') as f:

            image_data = f.read()
            image_type = imghdr.what(f.name)
            image_name = f.name

                newMessage.add_attachment(image_data,maintype='image',subtype=image_type,filename=image_name)

            with smtplib.SMTP_SSL('smtp.gmail.com',465) as smtp:

        smtp.login(Sender_Email,Password)
        smtp.send_message(newMessage)
try:
    for x in range(1):
        GPIO.output(26,1)
        sleep(2.5)
        GPIO.output(26,0)
        sleep(2.5)

except KeyboardInterrupt:
    GPIO.cleanup()
    GPIO.output(26,0)

    ## Loads the found template to charbuffer 1
    f.loadTemplate(positionNumber,0x01)

    ## Downloads the characteristics of template loaded in charbuffer 1
    characterics = str(f.downloadcharacteristics(0x01)).encode('utf-8')

    ## Hashes characteristics of template
    print('SHA-2 hash of template: ' + hashlib.sha256(characterics).hexdigest())

except Exception as e:
    print('Operation Failed!')
    print('Exception message: ' + str(e))
    exit(1)

解决方法

您需要在程序顶部定义函数。你只需要在 else 语句之后调用它。基本上,把

def find_newest_file(dir):
             os.system('fswebcam -r 1280x720 -S 3 --jpeg 90 --save /home/pi/Pictures/%H%M%S.jpg')
             types = ['*.png','*.jpg'] 
             files = []
             if not os.path.isdir(dir):
                 print(f'ERROR: {dir} does not exist. or it is not a valid folder')
                 exit()

在顶部,当你想使用它时

find_newest_file(foo)

祝您旅途愉快!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。