我正在编写一个要求输入的脚本。根据选项数量设置的变量很少。
option1 = '.\\Folder'
userChoice = input()
def func(userChoice):
pyautogui.locateOnScreen(userChoice)
但是,如果用户键入option1,则userChoice ='option1'而不是'。\ Folder',这会导致“没有此类文件或目录”错误。
我该如何解决这个问题?
答案 0 :(得分:0)
您可以使用python的try-except
。来自官方文档的示例:
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
更新:根据您的评论,我认为您需要执行以下操作:
choices={'option1' : './/Folder'}
userChoice = input()
try:
function=choices[userChoice]
except KeyError:
raise ValueError('invalid input')