1

所以这是我第一次尝试 Python 和 Raspberry Pi 编程。我的小项目是当我在 Twitter 上被提及时点亮 LED。一切都非常简单,下面显示的代码运行良好。我的问题与将前面提到的内容存储在文本文件而不是变量中有关。本质上,该代码检查printed_ids 变量以查找已经看到的tweet.ids 列表,以防止每次重新运行程序时LED 都持续闪烁。我的计划是在计划的作业中运行 python 代码,但我不希望每次重新启动 Pi 并运行程序时,程序都必须检查我提到的所有内容并将每次出现的情况写入print_ids 变量。因此,我的想法是将它们写入文本文件,以便程序在重新启动后仍然存在。

有什么想法/建议吗?

谢谢你的帮助。

import sys
import tweepy
import RPi.GPIO as GPIO ## Import GPIO library
import time ## Import 'time' library. Allows use of 'sleep'
GPIO.setmode(GPIO.BOARD) ## Use board pin numbering

CONSUMER_KEY = '******************'

CONSUMER_SECRET = '*****************'

ACCESS_KEY = '**********************'

ACCESS_SECRET = '*********************'

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
speed = 2

printed_ids = []

while True:
    for tweet in api.mentions_timeline():
            if tweet.id not in printed_ids:
                    print "@%s: %s" % (tweet.author.screen_name, tweet.text)
                    GPIO.setup(7,GPIO.OUT) ## Setup GPIO Pin 7 to OUT
                    GPIO.output(7,True)## Switch on pin 7
                    time.sleep(speed)## Wait
                    GPIO.output(7,False)## Switch off pin 7
                    f.open('out','w')
                    f.write(tweet.id)
                    ##printed_ids.append(tweet.id)
                    GPIO.cleanup()
                    time.sleep(60)  # Wait for 60 seconds.
4

1 回答 1

0

您正在寻找的东西称为“序列化”,Python为此提供了许多选项。也许最简单和最便携的就是json 模块

import json

# read:

with open('ids.json', 'r') as fp:
    printed_ids = json.load(fp) 
    # @TODO: handle errors if the file doesn't exist or is empty

# write:

with open('ids.json', 'w') as fp:
    json.dump(printed_ids, fp)
于 2013-10-10T12:29:46.897 回答