【发布时间】: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