如何在python中通过用户输入调用函数?

时间:2019-05-24 14:02:13

标签: python raspberry-pi

我正在研究带电机的机械按钮压脚。我已经写了一些代码。我有一些任务可以按不同的时间间隔按一下按钮(例如长按,短按,按3秒等)

from time import sleep    
import RPi.GPIO as GPIO    

DIR = 26   # Direction GPIO Pin    
STEP = 19  # Step GPIO Pin    
CW = 1     # Clockwise Rotation    
CCW = 0    # Counterclockwise Rotation    
SPR = 15   # Steps per Revolution (360 / 1.8)    

GPIO.setmode(GPIO.BCM)    
GPIO.setup(DIR, GPIO.OUT)    
GPIO.setup(STEP, GPIO.OUT)    
GPIO.output(DIR, CW)    

MODE = (14, 15, 18)   # Microstep Resolution GPIO Pins     
GPIO.setup(MODE, GPIO.OUT)    
RESOLUTION = {'Full': (0, 0, 0),    
              'Half': (1, 0, 0),    
              '1/4': (0, 1, 0),    
              '1/8': (1, 1, 0),    
              '1/16': (0, 0, 1),    
              '1/32': (1, 0, 1)}    

GPIO.output(MODE, RESOLUTION['Full'])    
step_count = SPR    
delay = .0208     

for x in range(step_count):    
    GPIO.output(DIR, CCW)    
    GPIO.output(STEP, GPIO.HIGH)    
    sleep(delay)    
    GPIO.output(STEP, GPIO.LOW)    
    sleep(delay)    

sleep(2)    
GPIO.output(DIR, CW)    
for x in range(step_count):    
    GPIO.output(STEP, GPIO.HIGH)    
    sleep(delay)    
    GPIO.output(STEP, GPIO.LOW)    
    sleep(delay)    

for x in range(step_count):    
    GPIO.output(DIR, CCW)    
    GPIO.output(STEP, GPIO.HIGH)    
    sleep(delay)    
    GPIO.output(STEP, GPIO.LOW)    
    sleep(delay)

sleep(8)    
GPIO.output(DIR, CW)     
for x in range(step_count):    
    GPIO.output(STEP, GPIO.HIGH)    
    sleep(delay)    
    GPIO.output(STEP, GPIO.LOW)    
    sleep(delay)    
GPIO.cleanup()

在上面的代码中,您可以看到我有两个间隔,即按下2秒和按下8秒。所以我想要一些东西,当我们运行代码时,它将询问您要使用哪个函数,然后在输入后将调用该特定时间间隔,并在该时间间隔内按下按钮。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我不确定我是否正确理解了要询问用户输入的上下文(因为大多数RP都是在无法轻易获得命令提示符的环境中使用的)。

但是,假设您确实在运行此Python脚本的某种外壳,这是一种方法:

def short_press():
    ...

def long_press():
    ...

actions = {'short': short_press, 'long': long_press}

command = input('Choose an action: ({})'.format(', '.join(actions.keys())))

if command in actions:
    actions[command]()
else:
    raise ValueError('{} is not a recognized action'.format(command)