我可以通过输入字符串来调用函数吗?

2024-09-23 10:27:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个函数,当文本输入等于命令时可以调用它。你知道吗

from os import system
from time import sleep
import ctypes

ctypes.windll.kernel32.SetConsoleTitleW('SimpleChat')

print('Hi, welcome to my basic chat engine!')

sleep(5)

system('cls')

username = input('Enter a username: ')

ctypes.windll.kernel32.SetConsoleTitleW('SimpleChat - ' + username)

system('cls')

def commands (command):
    commandlist = ['/help','/clear', '/commands']
    commanddict = {'/help' : 'help', '/clear' : 'clear', '/commands' : 'commands'}
    for possibility in commandlist:
        if command == possibilty:
            commanddict[possibility]()
            break 

def textInput (text):
    if text[0] == '/':
        commands(text)

第24行可以调用函数吗?我想象它的工作方式是,它将找到“可能性”键的条目,然后将其作为函数调用,但我不确定。你知道吗

如果前面的代码不起作用,您会怎么做?你知道吗


Tags: textfromimportusernamehelpsleepctypessystem
1条回答
网友
1楼 · 发布于 2024-09-23 10:27:36

假设有一个函数叫做helpclear,。。。在你的代码里。你知道吗

def help():
    print("help!")

然后,下面的commands函数将执行您想要的操作。 注意,在Python中,函数可以用作dictionary的值。你知道吗

def commands (command):
    command_dict = {'/help' : help, '/clear' : clear, '/commands' : commands}
    func = command_dict.get(command)

    if func is not None:
        func()
    else:
        print("I don't have such a command: %s" % command)

我想'/commands'中的值(command函数)应该更改为另一个函数。如果键入“commands”,程序将崩溃。你知道吗

相关问题 更多 >