【问题标题】:Python 3: Making a str object callablePython 3:使 str 对象可调用
【发布时间】:2014-06-04 07:57:59
【问题描述】:

我有一个接受用户输入的 Python 程序。我将用户输入存储为一个名为“userInput”的字符串变量。我希望能够调用用户输入的字符串...

userInput = input("Enter a command: ")
userInput()

由此,我得到错误:TypeError: 'str' object is not callable

目前,我的程序在做这样的事情:

userInput = input("Enter a command: ")
if userInput == 'example_command':
    example_command()

def example_command():
     print('Hello World!')

显然,这不是处理大量命令的一种非常有效的方式。 我想让 str obj 可调用 - 无论如何要这样做?

【问题讨论】:

  • 我认为您正在寻找的是 eval('string')。确保您仔细检查该字符串是什么,否则您将遇到一些重大的安全问题。您还必须在输入字符串的末尾添加“()”。
  • @Evan 即使 带有 繁重的检查,在用户输入上运行 eval 也可能不是一个好主意。你想要做的检查是“这个字符串是被批准的集合之一”,此时你不妨做一个字典查找。
  • @Evan 只是好奇,eval() 有什么作用以及为什么会导致安全问题?
  • 它尝试运行一个字符串。如果黑客想要进入您的系统,这将非常容易。他们只需要知道要调用哪些函数以及您拥有哪些变量。然后他们就继续他们的快乐之路。例如,如果您有一个带有一些变量“大小”的链表,则可以调用 eval,我认为也是 exec,“my_list.size = 0”并更改大小。有关这些的更多信息,请访问python docs
  • 谢谢@Evan,我现在明白了。

标签: python string object callable


【解决方案1】:

更好的方法可能是使用字典:

def command1():
    pass

def command2():
    pass

commands = {
    'command1': command1,
    'command2': command2
}

user_input = input("Enter a command: ")
if user_input in commands:
    func = commands[user_input]
    func()

    # You could also shorten this to:
    # commands[user_input]()
else:
    print("Command not found.")

本质上,您提供的是文字命令和您可能想要运行的函数之间的映射。

如果输入太多,您还可以使用local 关键字,它将返回当前范围内当前定义的每个函数、变量等的字典:

def command1():
    pass

def command2():
    pass

user_input = input("Enter a command: ")
if user_input in locals():
    func = locals()[user_input]
    func()

但这并不完全安全,因为恶意用户可能会输入与变量名称相同的命令或您不希望它们运行的​​某些函数,最终导致代码崩溃。

【讨论】:

  • 确认!你比我快 8 秒。干得好,先生,干得好!
  • 你们太聪明了:)
  • 谢谢!帮了我很多! ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-09
  • 2015-06-07
  • 2019-07-10
  • 2020-09-16
  • 1970-01-01
  • 1970-01-01
  • 2013-08-05
相关资源
最近更新 更多