Disclaimer: I have searched for a few days now, without much luck. If, despite that, there is already an answer somewhere, I would appreciate anyone pointing me to it.
I have been fooling around with RPi.GPIO and python (3.6 at the moment), but hit a minor snag when it comes to setting some attributes. I have been trying to find a way of using user input to set the attributes, along the lines of:
mode = input("Enter preferred mode (BCM/BOARD): ").upper()
mode_chosen = "GPIO." + mode
setattr(GPIO, "setmode", mode_chosen)
Obviously, the code above sets the attribute to GPIO.BCM
or GPIO.BOARD
as strings, which of course doesn't work. I could write an if-else loop that calls GPIO.setmode(GPIO.whatever)
, depending on the user input, but I was wondering if there was a more elegant way of doing it.
I am relatively new to python, so chances are I am missing some vital information here, so... thanks in advance to whomever takes the time to answer.
One way would be to use a dict:
choices = { "BCM": GPIO.BCM, "BOARD": GPIO.BOARD }
mode_chosen = choices[mode]