我有一个围绕 RPi.GPIO 模块构建的工作代码,我想优化某个我觉得它在外观上不太合适的部分(不是全部,只是代码的一部分)——除了我不知道怎么做。
这里是一个代码来举例说明上下文。 “违规”行就在注释 # question: how to optimize these lines? 的下方。我明确需要调用是单独的,原因之一是“在这种情况下,回调函数是按顺序运行的,而不是同时运行的”(引用自文档),我更喜欢我的特定用法。
可以找到 RPi.GPIO 的文档 here ,但没有太多可读的内容,我认为回调样式也可以在其他情况下找到。
#!/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 行(或其他通用随机数)行?
请您参考如下方法:
回调中的数字/名字是如何确定的?如果它是任意的,那么你现在可能做得很好。
也就是说,您可以创建一个数字函数元组列表,然后在 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 的麻烦。
不过,您现在所做的并没有错。
