【问题标题】:Raspberry pi script AttributeError: module 'datetime' has no attribute 'now'Raspberry pi 脚本 AttributeError:模块 'datetime' 没有属性 'now'
【发布时间】:2020-07-20 12:35:46
【问题描述】:

尝试在我的 pi 上运行脚本时出现此错误。我尝试导入日期时间,但也出现了错误。我是否缺少缩进或其他功能?

2020-07-20 13:26:56 - [INFO] doorbell: Listening for codes on GPIO 27
Connected with result code 0 12 384450 
Taking photo 

Traceback (most recent call last): 
    File "doorbell.py", line 79, in <module> 
        post_image()  
    File "doorbell.py", line 20, in post_image
        file_name ='image_' + str(datetime.now()) + '.jpg'  
AttributeError: module 'datetime' has no attribute 'now'

我已经通过sudo nohup python3 doorbell.py 拨打了脚本,这是脚本。

# combine the MQTT and RF receive codes 
import paho.mqtt.client as mqtt 
import paho.mqtt.publish as publish 
import picamera 
import argparse 
import signal 
import sys 
import time 
import datetime
import logging 
from rpi_rf import RFDevice 
rfdevice = None 
### camera 
camera = picamera.PiCamera() 
camera.vflip=True 
#
def post_image(): 
   print('Taking photo') 
   camera.capture('image.jpg') 
   file_name = 'image_' + str(datetime.now()) + '.jpg' 
   camera.capture(file_name)  # time-stamped image 
   with open('image.jpg', "rb") as imageFile: 
       myFile = imageFile.read() 
       data = bytearray(myFile) 
   client.publish('dev/camera', data, mqttQos, mqttRetained)  # 
   client.publish('dev/test', 'Capture!')  # to trigger an automation later
   print(file_name + 'image published') 
#
### MQTT 
broker = '192.168.1.15' 
topic ='dev/test' 
mqttQos = 0 
mqttRetained = False 
#
def on_connect(client, userdata, flags, rc): 
   print("Connected with result code "+str(rc)) 
   client.subscribe(topic) 
# The callback for when a PUBLISH message is received from the server.
# 
def on_message(client, userdata, msg): 
   payload = str(msg.payload.decode('ascii'))  # decode the binary string 
   print(msg.topic + " " + payload) 
   process_trigger(payload) 
#
def process_trigger(payload): 
   if payload == 'ON': 
       print('ON triggered') 
       post_image() 
#
client = mqtt.Client() 
client.on_connect = on_connect    # call these on connect and on message 
client.on_message = on_message 
client.username_pw_set(username='',password='')  # need this 
client.connect(broker) 
client.loop_start()    #  run in background and free up main thread 
### RF 
#
def exithandler(signal, frame): 
   rfdevice.cleanup() 
   sys.exit(0) 
logging.basicConfig(level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S', 
                   format='%(asctime)-15s - [%(levelname)s] %(module)s: %(message)s', ) 
parser = argparse.ArgumentParser(description='Receives a decimal code via a 433/315MHz GPIO device') 
parser.add_argument('-g', dest='gpio', type=int, default=27, 
                   help="GPIO pin (Default: 27)") 
args = parser.parse_args() 
signal.signal(signal.SIGINT, exithandler) 
rfdevice = RFDevice(args.gpio) 
rfdevice.enable_rx() 
timestamp = None 
logging.info("Listening for codes on GPIO " + str(args.gpio)) 
code_of_interest = '384450' 
#
while True: 
   if rfdevice.rx_code_timestamp != timestamp: 
       timestamp = rfdevice.rx_code_timestamp 
       print(str(rfdevice.rx_code)) 
       if str(rfdevice.rx_code) == code_of_interest: 
           post_image() 
           time.sleep(1)  # prevent registering multiple times
   time.sleep(0.01) 
rfdevice.cleanup() 

请帮助解决这个问题。我试图跟随一个门铃,当它让射频代码在家庭助理上运行时,它就可以工作。我可以从 HA 手动运行脚本,当我运行上面的脚本时会出错。

我已经尝试了一个星期来解决这个问题,但我无法解决。我的编码不是很好,但我可以做基本的python。

谢谢。

【问题讨论】:

  • 你应该使用:datetime.datetime.now(),或者从datetime模块导入datetime对象

标签: python python-3.x raspberry-pi home-assistant


【解决方案1】:

尝试改变这个:

def post_image(): 
   print('Taking photo') 
   camera.capture('image.jpg') 
   file_name = 'image_' + str(datetime.now()) + '.jpg' 
   camera.capture(file_name)  # time-stamped image 
   with open('image.jpg', "rb") as imageFile: 
       myFile = imageFile.read() 
       data = bytearray(myFile) 
   client.publish('dev/camera', data, mqttQos, mqttRetained)  # 
   client.publish('dev/test', 'Capture!')  # to trigger an automation later
   print(file_name + 'image published') 

进入这个:

def post_image(): 
   print('Taking photo') 
   camera.capture('image.jpg') 
   file_name = 'image_' + str(datetime.datetime.now()) + '.jpg' 
   camera.capture(file_name)  # time-stamped image 
   with open('image.jpg', "rb") as imageFile: 
       myFile = imageFile.read() 
       data = bytearray(myFile) 
   client.publish('dev/camera', data, mqttQos, mqttRetained)  # 
   client.publish('dev/test', 'Capture!')  # to trigger an automation later
   print(file_name + 'image published') 

【讨论】:

    【解决方案2】:

    datetime module 有一个 class datetime,它具有您想要的功能。

    所以使用: datetime.datetime.now() 而不是 datetime.now()

    如果您希望保持原样,请将您的导入语句从 import datetime 更改为 from datetime import datetime

    To read more about the import system, the docs are your friend.

    【讨论】:

      猜你喜欢
      • 2018-11-11
      • 2013-10-29
      • 2019-10-06
      • 2017-08-18
      • 2017-04-02
      • 2022-01-27
      • 1970-01-01
      • 2018-04-14
      • 2019-02-18
      相关资源
      最近更新 更多