英文:
Is there a better way to take an input and check it against a list of commands?
问题
我正在工作的程序具有终端样式界面。我有一段检查输入的代码块,使用我自己制作的自定义库:
try:
rawcmd = typing_.typingInput(' > ').split() # 将命令拆分为2部分。
try:
global cmd
cmd = rawcmd[0]
except IndexError:
cmd = ' '
然后进入一大堆 if elif 语句的阶梯(我只提供了一部分):
if cmd == '?' or cmd =='help': # 列出所有命令及其功能。
# 这里只是一些填充代码
elif cmd == 'ls': # 列出当前工作目录以及该目录中的所有文件。
typing_.typingPrint('Current Working Directory: ' +os.getcwd()+'\n')
delimiter = '\n'
files = delimiter.join(os.listdir())
typing_.typingPrint(files+'\n')
elif cmd == 'cd': # 切换到提供的目录
try:
path = os.path.abspath(rawcmd[1])
os.chdir(path)
except FileNotFoundError:
typing_.typingPrint('No Directory with that name')
elif cmd == 'mkdir': # 在文件系统中创建新文件夹。
name=rawcmd[1]
os.mkdir(name)
elif cmd == 'mkfile': # 运行 CreateFile() 函数
name = rawcmd[1]
createFile(name)
elif cmd == 'rmvfile': # 运行 DeleteFile() 函数
name = rawcmd[1]
deleteFile(name)
elif cmd == 'editfile': # 运行 EditFile() 函数
name = rawcmd[1]
editFile(name)
elif cmd == 'readfile': # 运行 ReadFile() 函数
name = rawcmd[1]
viewFile(name)
elif cmd == 'rmvtree': # 删除提供的文件夹及其中的所有文件。
name = rawcmd[1]
shutil.rmtree(name)
elif cmd == 'exit': # 退出终端。
有没有更高效、更易于其他人阅读的更好方法来做到这一点?
英文:
The program I am working atm has a terminal-style interface. I have a block of code that checks for the input with a custom library I made :
try:
rawcmd = typing_.typingInput('> ').split() # Splits the command into 2 parts.
try:
global cmd
cmd = rawcmd[0]
except IndexError:
cmd = ' '
and then that leads into a large ladder of if elif statements (I'll only provide a few):
if cmd == '?' or cmd =='help': # Lists out all the commands and what each one does.
# Just some filler code here
elif cmd == 'ls': # Lists out the Current Working Directory, aswell as all the files within that directory.
typing_.typingPrint('Current Working Directory: ' +os.getcwd()+'\n')
delimiter = '\n'
files = delimiter.join(os.listdir())
typing_.typingPrint(files+'\n')
elif cmd == 'cd': # Changes the directory to the supplied one
try:
path = os.path.abspath(rawcmd[1])
os.chdir(path)
except FileNotFoundError:
typing_.typingPrint('No Directory with that name')
elif cmd == 'mkdir': # Creates a new Folder in the file system.
name=rawcmd[1]
os.mkdir(name)
elif cmd == 'mkfile': # Runs the CreateFile() function
name = rawcmd[1]
createFile(name)
elif cmd == 'rmvfile': # Runs the DeleteFile() function
name = rawcmd[1]
deleteFile(name)
elif cmd == 'editfile': # Runs the EditFile() function
name = rawcmd[1]
editFile(name)
elif cmd == 'readfile': # Runs the ReadFile() function
name = rawcmd[1]
viewFile(name)
elif cmd == 'rmvtree': # Deletes the supplied folder and all files within.
name = rawcmd[1]
shutil.rmtree(name)
elif cmd == 'exit': # Quits the Terminal.
Is there a better way to do this that would be more efficient, and easier for other people to read?
答案1
得分: 4
确保每个菜单命令都可以表示为一个函数,这样你就不需要在处理菜单的代码内部编写大块的实现代码:
def cmd_help():
# 这里只是一些填充代码
pass
def ls():
typing_.typingPrint('当前工作目录: ' + os.getcwd() + '\n')
delimiter = '\n'
files = delimiter.join(os.listdir())
typing_.typingPrint(files + '\n')
def cd(name):
try:
path = os.path.abspath(name)
os.chdir(path)
except FileNotFoundError:
typing_.typingPrint('没有找到该名称的目录')
# 构建命令名称到函数的字典
cmd_funcs = {
'?': cmd_help,
'help': cmd_help,
'ls': ls,
'cd': cd,
'mkdir': os.mkdir,
'mkfile': createFile,
'rmvfile': deleteFile,
'editFile': editFile,
'readfile': viewFile,
'rmvtree': shutil.rmtree,
'exit': exit,
}
# 将菜单实现为以下方式之一:
# 方法1
if rawcmd[0] in cmd_funcs:
cmd_funcs[rawcmd[0]](*rawcmd[1:])
# 或者方法2
try:
cmd_funcs[rawcmd[0]](*rawcmd[1:])
except KeyError:
print("无效命令:", rawcmd[0])
except TypeError:
print("无效命令参数:", *rawcmd[1:])
英文:
First make sure that each menu command can be represented as a function, so you don't need blocks of implementation inside the code that handles your menu:
def cmd_help():
# just some filler code here
pass
def ls():
typing_.typingPrint('Current Working Directory: ' +os.getcwd()+'\n')
delimiter = '\n'
files = delimiter.join(os.listdir())
typing_.typingPrint(files+'\n')
def cd(name):
try:
path = os.path.abspath(name)
os.chdir(path)
except FileNotFoundError:
typing_.typingPrint('No Directory with that name')
Now you can build a dict of command names to functions:
cmd_funcs = {
'?': cmd_help,
'help': cmd_help,
'ls': ls,
'cd': cd,
'mkdir': os.mkdir,
'mkfile': createFile,
'rmvfile': deleteFile,
'editFile': editFile,
'readfile': viewFile,
'rmvtree': shutil.rmtree,
'exit': exit,
}
and implement your menu as:
if rawcmd[0] in cmd_funcs:
cmd_funcs[rawcmd[0]](*rawcmd[1:])
or perhaps something like:
try:
cmd_funcs[rawcmd[0]](*rawcmd[1:])
except KeyError:
print("Invalid command:", rawcmd[0])
except TypeError:
print("Invalid command arguments:", *rawcmd[1:])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论