Python程序忽略按钮输入

时间:2018-04-27 01:39:43

标签: python twitter raspberry-pi bots

我是python和linux的新手,我最近在我的Raspberry Pi中设置了一个推特机器人,让他们玩得很开心。我想建立一个系统,每当我按下按钮时,我的RasPi就会发送一条推文。我按照https://raspberrypihq.com/use-a-push-button-with-raspberry-pi-gpio上的说明设置了基本输入。

我有两个.py文件,tweet_test.py和buttonPress.py

tweet_test:

#!/usr/bin/env python
import os
import random
from twython import Twython


# your twitter consumer and access information goes here
apiKey = ''
apiSecret = ''
accessToken = ''
accessTokenSecret = ''

api = Twython(apiKey,apiSecret,accessToken,accessTokenSecret)


messages = [
    "A button was pressed!!",
    "My creator pressed a button.",
    "This tweet was triggered by a button press.",
]

message = random.choice(messages)

api.update_status(status=message)
print("Tweeted: " + message) 

buttonPress:

import tweet_test
import RPi.GPIO as GPIO #Import Raspberry Pi GPIO library


def button_callback(channel):
    tweet_test
    print("Button was pushed!")

GPIO.setwarnings(False) #Ignore warning for now
GPIO.setmode(GPIO.BOARD) #Use physical pin numbering
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #Set pin 10 to be an 
input pin and set initial value to be pulled low (off)

GPIO.add_event_detect(10,GPIO.RISING,callback=button_callback) #Set up 
event on pin 10 rising edge

message = input("Press enter to quit\n\n") #Run until someone presses 
enter

GPIO.cleanup() #Clean Up

但是,当我在命令行中运行buttonPress.py时,它首先做的是推文,甚至没有从按钮接收任何输入。然后,它开始接收按钮输入,但不会发送任何内容。请帮忙!

示例输出:

user1@raspberrypi:~/TwitterBot $ sudo python buttonPress.py
Tweeted: A button was pressed!!
Press enter to quit

Button was pushed!
Button was pushed!
Button was pushed!

1 个答案:

答案 0 :(得分:0)

你最初导入tweet_test.py并且它将首先运行,它将按预期运行,即发送推文。您需要将推文部分包装为一个函数,以便它只在调用它时运行:

在tweet_test.py

def tweet():
    message = random.choice(messages)
    api.update_status(status=message)
    print("Tweeted: " + message) 

在buttonPress.py

在你的button_callback中调用tweet()函数,如下所示:

def button_callback(channel):
    tweet()
    print("Button was pushed!")

或者,只需将推文部分移至button_call函数,并将它们合并到button_callback中:

def button_callback(channel):
    message = random.choice(messages)
    api.update_status(status=message)
    print("Button was pushed! Tweeted: %s" % message)

更新

请同时将import tweet_test行更改为from tweet_test import *