【问题标题】:optimize portion of code for similar event callbacks in RPi.GPIO (python on Raspberry Pi)优化 RPi.GPIO 中类似事件回调的代码部分(Raspberry Pi 上的 python)
【发布时间】:2015-11-21 22:47:54
【问题描述】:

我有一个围绕 RPi.GPIO 模块构建的工作代码,并且想要优化我觉得它在外观上不适合的某个部分(不是整个,只是代码的一部分)——除了我不这样做知道怎么做。

这是一个示例上下文的代码。 “违规”行就在评论 # question: how to optimize these lines? 的下方。我明确需要单独调用,原因之一是“在这种情况下,回调函数是按顺序运行的,而不是同时运行的”(引用自文档),我更喜欢我的特定用途。

可以在here 找到 RPi.GPIO 的文档,但没有太多可阅读的内容,我认为回调样式也可以在其他情况下找到。

#!/usr/bin/env python

# RPi.GPIO module for Raspberry Pi https://pypi.python.org/pypi/RPi.GPIO
import RPi.GPIO as GPIO
import sys
import os
import time

class test(object):
    def __init__(self):
        pass

    def main(self):
        # consider BCM port numbering convention
        GPIO.setmode(GPIO.BCM)
        ports = [16, 20, 23]    # 3 ports only for this example, might be n ports
                                # actual port number is not relevant to question
        for i, port in enumerate(ports):
            # setup port direction & internal pull-up
            GPIO.setup(port, GPIO.IN, pull_up_down=GPIO.PUD_UP)
            # setup interrupt movement sense
            GPIO.add_event_detect(port, GPIO.FALLING)

        # question: how to optimize these lines? (compact in a loop or something)
        GPIO.add_event_callback(16, self.do_something_1)
        GPIO.add_event_callback(20, self.do_something_2)
        GPIO.add_event_callback(23, self.do_something_3)
        # etc. (might be n event callbacks, not just 3)

        while True:
            time.sleep(1)

    # some internal calls or even as separate external file(name) modules
    def do_something_1(self, from_port):    # for first port in ports
        print("called from port %s" % (from_port))
    def do_something_2(self, from_port):    # for second port in ports
        print("called from port %s" % (from_port))
    def do_something_3(self, from_port):    # for third port in ports
        print("called from port %s" % (from_port))
    # etc. (might be n defined functions, not just 3)

if __name__ == "__main__":
    try:
        app = test()
        app.main()
    except KeyboardInterrupt:
        print (" exit via Ctrl+C")
    finally:
        GPIO.cleanup()
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)

那么,问题:我应该如何处理这 3 行(或通用的其他随机数)?

【问题讨论】:

    标签: python raspberry-pi


    【解决方案1】:

    回调中的数字/名称是如何确定的?如果它是任意的,那么您目前可能做得很好。

    也就是说,您可以创建一个数字函数元组列表,然后在 for 循环中调用它们?但这并没有更好的恕我直言。

    callback_pairs = [(16, "do_something_1"), (20, "do_something_2"), (23, "do_something_3")]
    for n, fname in callback_pairs: 
        GPIO.add_event_callback(n, getattr(self, fname))
    

    您也可以通过在对列表中直接引用self.do_something_[123] 来摆脱getattr 的讨厌。

    不过,你现在所做的并没有错。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-15
      • 1970-01-01
      • 2016-07-23
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多