python - 按下按钮时执行功能

标签 python python-2.7

首先,这是我第一次工作和使用python,所以请耐心等待:)

我正在尝试破解亚马逊的破折号按钮来切换我的飞利浦 hue 灯,我设法找到所有必需的元素和代码并对其进行编辑以满足我的需要。

我现在遇到的问题是,如果我运行脚本,我想运行的 python 函数会立即执行,不会等待按下按钮...

这是一些代码:

from pydhcplib.dhcp_network
import *
import requests, json

bridgeIP = "{{mybridgeIP}}"
user = "{{philipsUserID}}"
dashMac = "{{dashMacAddress}}"
lightID = "4"

def do_something():
    print("button has been pressed")

def toggleLight(lightID):
    url = "http://" + bridgeIP + "/api/" + user + "/lights/" + lightID
    r = requests.get(url)
    data = json.loads(r.text)
    if data["state"]["on"] == False:
      r = requests.put(url + "/state", json.dumps({
        'on': True
      }))
    elif data["state"]["on"] == True:
      r = requests.put(url + "/state", json.dumps({
        'on': False
        }))


netopt = {'client_listen_port':"68", 'server_listen_port':"67", 'listen_address':"0.0.0.0"}

class Server(DhcpServer):
    def __init__(self, options, dashbuttons):
        DhcpServer.__init__(self, options["listen_address"],
                                options["client_listen_port"],
                                options["server_listen_port"])
        self.dashbuttons = dashbuttons

    def HandleDhcpRequest(self, packet):
        mac = self.hwaddr_to_str(packet.GetHardwareAddress())
        self.dashbuttons.press(mac)


    def hwaddr_to_str(self, hwaddr):
        result = []
        hexsym = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']
        for iterator in range(6) :
            result += [str(hexsym[hwaddr[iterator]/16]+hexsym[hwaddr[iterator]%16])]
        return ':'.join(result)

class DashButtons():
    def __init__(self):
        self.buttons = {}

    def register(self, mac, function):
        self.buttons[mac] = function

    def press(self, mac):
        if mac in self.buttons:
            self.buttons[mac]()
            return True
        return False


dashbuttons = DashButtons()
dashbuttons.register(dashMac, do_something)
dashbuttons.register(dashMac, toggleLight(lightID))
server = Server(netopt, dashbuttons)

while True :
    server.GetNextDhcpPacket()

我的问题是 do_something() 被正确调用(当我按下按钮时)但是 toggleLight(lightID) 在我运行脚本时被调用..

我不明白为什么,他们看起来和我一模一样..

你能帮我理解一下吗?谢谢

最佳答案

用这条线

dashbuttons.register(dashMac, toggleLight(lightID))

您执行 toggleLight(lightID) 并将该调用的结果绑定(bind)到 function 参数。由于该函数需要一个参数,因此您也不能只传递 toggleLight。相反,使用 lambda 函数:

dashbuttons.register(dashMac, lambda: toggleLight(lightID))

这将创建一个新的匿名函数,该函数不接受任何参数,并且在被按钮调用时将调用 toggleLight(lightID)

关于python - 按下按钮时执行功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42683552/

相关文章:

python - len() 与 numpy 数组上的 __len__ 相比

python - 使用 python 将数据组织到适当的列中

python - 如何向 selenium chrome webdriver 添加多个扩展

python - 在模拟上调用 python 内置 dict

python - python 中是否存在 __bin__ (或 __binary__)运算符?

python - 无法将 os.system 与 'æ' 、 'ø' 或 'å' 一起使用

python - AtributteError "object has no attribute"- 如何在不尝试/除外的情况下防止 - 访问模型字段

python - 将 Pandas 单元格中的文本(json 对象?)转换为列

Django POST 方法单元测试失败,出现 Assertionerror 401

python - 不可能的反向引用