首页 > 解决方案 > 如何在python中通过用户输入调用函数?

问题描述

我正在研究一个带电机的机械按钮按压器。我写了一些代码。我有一些任务要按不同的时间间隔按下按钮(例如长按、短按、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 秒。所以我想要一些东西,当我们运行代码时,它会询问您要使用哪个函数,然后在给出输入后它将调用该特定间隔,并且该按钮将在该间隔内被按下。任何帮助将不胜感激。

标签: pythonraspberry-pi

解决方案


我不确定我是否正确理解了您想要请求用户输入的上下文(因为大多数 RP 都用于首先无法轻松获得命令提示符的环境)。

但是假设你确实有某种 shell 来运行这个 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)

推荐阅读