2016-04-30 2 views
0
import threading 
import time 

def cold_temp(): 
    # Open the file that we viewed earlier so that python can see what is in it. Replace the serial number as before. 
    tfile = open("/sys/bus/w1/devices/28-021571bf69ff/w1_slave") 
    # Read all of the text in the file. 
    text = tfile.read() 
    # Close the file now that the text has been read. 
    tfile.close() 
    # Split the text with new lines (\n) and select the second line. 
    secondline = text.split("\n")[1] 
    # Split the line into words, referring to the spaces, and select the 10th word (counting from 0). 
    temperaturedata = secondline.split(" ")[9] 
    # The first two characters are "t=", so get rid of those and convert the temperature from a string to a number. 
    temperature = float(temperaturedata[2:]) 
    # Put the decimal point in the right place and display it. 
    temperature = temperature/1000 
    return temperature 

output = cold_temp()  
f = open('/var/www/html/coldtemp.html', 'w') 
print >> f, output 
f.close() 
cold_temp() 

Я попытался выше и простойPython не работает каждый второй

def cold_temp(): 
    while True: 
     # Open the file that we viewed earlier so that python can see what is in it. Replace the serial number as before. 
     tfile = open("/sys/bus/w1/devices/28-021571bf69ff/w1_slave") 
     # Read all of the text in the file. 
     text = tfile.read() 
     # Close the file now that the text has been read. 
     tfile.close() 
     # Split the text with new lines (\n) and select the second line. 
     secondline = text.split("\n")[1] 
     # Split the line into words, referring to the spaces, and select the 10th word (counting from 0). 
     temperaturedata = secondline.split(" ")[9] 
     # The first two characters are "t=", so get rid of those and convert the temperature from a string to a number. 
     temperature = float(temperaturedata[2:]) 
     # Put the decimal point in the right place and display it. 
     temperature = temperature/1000 
     return temperature 

     output = cold_temp()  
     f = open('/var/www/html/coldtemp.html', 'w') 
     print >> f, output 
     f.close() 
     time.sleep(1) 

Я хотел запустить скрипт каждый второй. Оба вышеперечисленного запускаются после этого.

+1

В чем вопрос? – TehSphinX

+3

Что именно происходит? Сбой сценария? Выполняется ли он каждые 1,1 секунды или не все? –

+0

Покажите нам что-нибудь. –

ответ

2

Ваш цикл while находится не в том месте. Я взял на себя смелость изменить код, чтобы использовать предложения with, который является более стандартным способом открытия файлов, но он сломается, если у вас действительно старый питон.

import threading 
import time 

def cold_temp(): 
    # Open the file that we viewed earlier so that python can see what is in it. Replace the serial number as before. 
    with open("/sys/bus/w1/devices/28-021571bf69ff/w1_slave") as tfile: 
     # skip first line, keep second line 
     next(tfile) 
     secondline = next(tfile) 
    # Split the line into words, referring to the spaces, and select the 10th word (counting from 0). 
    temperaturedata = secondline.split(" ")[9] 
    # The first two characters are "t=", so get rid of those and convert the temperature from a string to a number. 
    temperature = float(temperaturedata[2:]) 
    # Put the decimal point in the right place and display it. 
    temperature = temperature/1000 
    return temperature 

while True: 
    output = cold_temp()  
    with open('/var/www/html/coldtemp.html', 'w') as f: 
     print >> f, output 
    time.sleep(1) 
+0

Спасибо! Это прекрасно работает. Решили проверить, поставив термометр в рот, а затем ледяную воду. Великий –

2

Вы можете использовать модуль sched, чтобы запланировать что-то многократно, будь то каждые два часа или каждую секунду.

Если ваша функция занимает больше одной секунды для запуска (маловероятно для проверки температуры), тогда у вас будет задержка.

Вы также увидите некоторый «дрейф» за это время, потому что время, в течение которого ваша функция запускается, поскольку она многократно запланирована. Все крошечные «биты» времени, в течение которого ваша функция будет работать, в конечном итоге будут складываться.

например. -

import sched, time 

s = sched.scheduler(time.time, time.sleep) 
def some_function(): 

    print time.time() 
    s.enter(1, 0, some_function) 

s.enter(1, 0, some_function) 
s.run() 
+0

Я не могу заставить это работать, но спасибо. –

+0

Также существует 5 аргументов для 's.enter' –

1

Первый запускается один раз, потому что вы не дали ему возможности многократно запускать его. Вторая обращается к return, которая выходит из функции (и, следовательно, цикла), прежде чем она даже имеет возможность вывести что-либо. Удалите return и просто используйте temperature для значения output.

+0

Не вызывает ошибок, но не записывает вывод в файл html –

+0

Не вызывайте' output = cold_temp() '. Это рекурсия: 'cold_temp' продолжает называть себя навсегда и никогда не попадает в выходную часть. Просто напечатайте значение 'temperature'. –

+0

все еще не пишет .. 'температура = температура/1000 е = открыт ('/ вар/WWW/HTML/coldtemp.html', 'ж') печати >> F, температура f.close () time.sleep (1) ' –

Смежные вопросы