Python Скрипт не просыпается - PullRequest
0 голосов
/ 08 мая 2020

У меня есть скрипт, который делает скриншоты нашего сада, а после заката он делает замедленную съемку из фотографий. Я отправляю сценарий спать до следующего дня, но он не проснулся. Я не могу найти проблему. возможно, вы можете мне помочь, этот сценарий работает в Docker на Fedora, а Fedora не может работать python3 -u /script >& output & ... прикрепил мой сценарий (к сожалению, я все еще новичок)

import datetime
from astral import LocationInfo
from astral.sun import sun
from time import sleep
import os
import requests
import pika
import sys


channel_id = '#####'
class pikacord:
    def push_msg(self, msg):
        url = ('amqp://#####')
        params = pika.URLParameters(url)
        connection = pika.BlockingConnection(params)
        channel = connection.channel()
        channel.basic_publish(exchange='amq.topic', routing_key='discord.msg', 
        properties=pika.BasicProperties(
            headers={'channelId': channel_id}),
            body=(msg))
        connection.close()
        return connection.close

class Sunclock:
    def suntime(self):
        #Locationdata
        l = LocationInfo('City', 'Deutschland', 'Europe/Berlin', ######cords, ######cords)

        #Suncal

        #sunrise
        s = sun(l.observer, date=datetime.date.today())
        sunrise = s["sunrise"]
        self.sunrisetime = sunrise.strftime('%H:%M')


        #sunset
        sunset = s["sunset"]
        self.sunsettime = sunset.strftime('%H:%M')


        #current
        current = datetime.datetime.utcnow()
        self.currenttime = current.strftime('%H:%M')
        self.currenttimelong = current.strftime('%Y-%m-%d %H:%M')

        #date
        self.date = datetime.date.today()


#init def suntime
sunfloat = Sunclock()
sunfloat.suntime()

try_count = 0
loopi = True
while loopi == True:
    sunfloat = Sunclock()
    sunfloat.suntime()
    get_sunset = sunfloat.sunsettime
    get_sunrise = sunfloat.sunrisetime
    get_current = sunfloat.currenttime
    print (get_sunrise)
    print (get_sunset)
    print (get_current)
    if try_count <=3:
        try:
            if get_current >= get_sunrise and get_current <= get_sunset:
                #take Pictures 
                foldercheck = os.path.isdir('/apps/media')
                if foldercheck == False:
                    os.mkdir('/apps/media')
                    os.mkdir('/apps/motioneye')
                else:
                    print ('Folder exist')

                os.chdir('/apps/media')
                take_pic = 'curl ' "'http://######/picture/3/current/?_username=######&_signature=########'" ' --output `date +%Y-%m-%d_%H-%M-%S`snapshot.jpg'
                print (take_pic)
                os.system(take_pic)
                print ('please smile')
                sleep(180)           
            else:
                #make Timelapse
                os.chdir('/apps/media/')
                delete = 'sudo rm /apps/media/*snapshot.jpg'
                move = 'mv *.mp4 /apps/motioneye/Camera3'
                timelapse = 'ffmpeg -r 30 -pattern_type glob -i "*snapshot.jpg" -c:v libx264 -pix_fmt yuv420p -movflags +faststart `date +%Y-%m-%d_%H-%M-%S`timelapse.mp4'
                os.system(timelapse)
                os.system(move)
                os.system(delete)
                #time to sleep 
 Problem--->        while get_sunrise > get_current or get_sunset < get_current:
                    get_sunset = sunfloat.sunsettime
                    get_sunrise = sunfloat.sunrisetime
                    get_current = sunfloat.currenttime
                    sleep(300)
                print ('good morning sun is rising at :' + get_sunrise)
        except Exception as e:
            print ('somthing was wrong:' +str(e))
            try_count += +1
            if try_count ==3:
                broker = pikacord()
                text = ('Greencam abort, to many errors please help:' +str(e))
                print ('abort mission!!!')
                #send abort Massage to Discord
                discord = broker.push_msg(text)
            else:
                sleep(300)
    else:
        loopi = False

1 Ответ

0 голосов
/ 08 мая 2020

Объяснение

Причина того, почему ваш скрипт еще не «проснулся», заключается в том, что вы либо не понимаете, как работают классы, либо просто пропустили часть вашего кода (я предположим, что это первое, так как ответ будет более информативным).

Класс состоит из методов (функций) и атрибутов (переменных). Их можно использовать напрямую (статически) или через экземпляры. В вашем случае вы пытаетесь использовать класс Sunclock в качестве экземпляра с именем sunfloat: sunfloat = Sunclock().

В следующей строке вы запускаете метод suntime, используя sunfloat, и это устанавливает атрибуты: sunrisetime, sunsettime, curenttime, curenttimelong и date. После этого вы просто назначаете переменные некоторым из этих атрибутов.

Теперь давайте go к root проблемы:

while get_sunrise > get_current or get_sunset < get_current:
    get_sunset = sunfloat.sunsettime
    get_sunrise = sunfloat.sunrisetime
    get_current = sunfloat.currenttime
    sleep(300)

То, что вы делаете здесь, - это присваивание переменные к одним и тем же атрибутам все время. sunfloat.sunsettime, sunfloat.sunrisetime и sunfloat.currenttime никогда не изменятся, пока вы находитесь в l oop, они не получат новые значения из воздуха - их значения необходимо изменить.

Решение

Чтобы изменить значения атрибутов, вы захотите снова вызвать метод suntime. Метод установит для всех атрибутов самые актуальные значения:

while get_sunrise > get_current or get_sunset < get_current:
    # All the attributes get re-assigned to the most up-to-date values.
    sunfloat.suntime()

    get_current = sunfloat.currenttime
    get_sunset = sunfloat.sunsettime
    get_sunrise = sunfloat.sunrisetime

    sleep(300)
...