如何停止导入当前模块?
例如,我们说我有这段代码:
try:
import RPi.GPIO as GPIO
except ImportError:
# not on a raspberry pi, warning functions do nothing
warn_with_led = lambda: None
warn_with_sound = lambda: None
else:
# on a raspberry pi
def warn_with_led():
GPIO.setmode(GPIO.BCM)
# more stuff
# more stuff
# more stuff
GPIO.cleanup()
def warn_with_sound():
GPIO.setmode(GPIO.BCM)
# more stuff
# more stuff
# more stuff
GPIO.cleanup()
不是用额外的缩进级别(由import try / except创建)编写整个代码,有没有办法从当前文件退出/返回?是否有解除缩进的解决方案,可能是:
try:
import RPi.GPIO as GPIO
except ImportError:
# not on a raspberry pi, warning functions do nothing
warn_with_led = lambda: None
warn_with_sound = lambda: None
exit_this_module() # <========= I would like to exit this file only
def warn_with_led():
GPIO.setmode(GPIO.BCM)
# more stuff
# more stuff
# more stuff
GPIO.cleanup()
def warn_with_sound():
GPIO.setmode(GPIO.BCM)
# more stuff
# more stuff
# more stuff
GPIO.cleanup()