linecache从外部.txt fi读取行时的Python问题

2024-09-28 19:05:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在整理我的第一个Python项目。我正在运行下面的Python代码,但在linecache.getline. 我要它打开斯托拉格.txt文件。检查数字是否为0。如果是,请将其更改为1-播放音乐并打开LED。然后把它切换到2,它不会再播放音乐,每次我关机启动我的树莓派。任何建议都会非常惊人。在

我的存储.txt结果是这样的:

0

0

0

我想应该是这样的:

^{pr2}$

我的python代码如下所示:

import requests
import pygame
import RPi.GPIO as GPIO 
from BeautifulSoup import BeautifulSoup
import linecache


pygame.mixer.init()
pygame.mixer.music.load('chaching.wav')


GPIO.setmode(GPIO.BCM)
#Im using pin 23 for the led. 
GPIO.setup(21, GPIO.OUT)
#Im using pin 4 as a basic switch in replacement for a motion sensor.
GPIO.setup(4, GPIO.IN)

#Cleans up the number taken from my php file.
Soup = BeautifulSoup

#Subscriber number
sub_num = 0

#goal one value
goal1 = 93  
#goal1 celebration flag pulled from the txt file. Line 1 of the doc. 
goal1cel = linecache.getline('storage.txt', 1)
goal2 = 100
goal2cel = linecache.getline('storage.txt', 2)
goal3 = 150
goal3cel= linecache.getline('storage.txt', 3)

detectDaniel = 0


while True:
    response = requests.get('http://www.bringyourownlaptop.com/php-test')
    html= response.content

    soup = BeautifulSoup(html)
    num = soup.find('section')
    sub_num = int(num.contents[0].strip())

    # figure out if goal have been reached and set the appropriate goal celebration flag
    if sub_num == goal1 and goal1cel == 0:
        goal1cel = 1

    if sub_num == goal2 and goal2cel == 0:
        goal2cel = 1

    if sub_num == goal3 and goal3cel == 0:
        goal3cel = 1

    # This passed the current status of the goal1cel e.g. 0 not done, 1 current, 2 finished. 
    text_file = open("storage.txt", "w")
    #This added it to the text document with slash n used as a line break. Weve also had to change the value to a string instead of a integer. 
    text_file.write(str(goal1cel)+"\n"+str(goal2cel)+"\n"+str(goal3cel))
    #closes the file. 
    text_file.close()


    detectDaniel = 1

    # checks if celebrations need to happen from goal celebration flags
    if goal1cel == 1 and detectDaniel == 1:
        GPIO.output(21, True)
        pygame.mixer.music.play()
        while pygame.mixer.music.get_busy() == True:
            continue
        print("Goal 1 reached!")
        goal1cel = 2

    if goal2cel == 1 and detectDaniel == 1:
        GPIO.output(21, True)
        pygame.mixer.music.play()
        while pygame.mixer.music.get_busy() == True:
                        continue
        print("Goal 2 reached!")
        goal2cel = 2

    if goal3cel == 1 and detectDaniel == 1:
        print("Goal 3 reached!")
        goal3cel = 2


    print(sub_num)
    print(detectDaniel)

Tags: andtheimporttxtgpioifpygamenum
1条回答
网友
1楼 · 发布于 2024-09-28 19:05:47

您的错误在于假设linecache.getline只返回一个整数。如果在解释器中运行它,它将返回字符串'0\n',这是一个字符串。在

在你得到这行之后,你需要找到一些方法来简单地得到你想要的数字(如果它们只会是1个字符的值,那么你可以只取第一个字符并与字符进行比较,例如if goal1cel == '1'。在

相关问题 更多 >