允许用户输入函数的Python代码

允许用户输入函数的Python代码,python,Python,在我的python入门课程中,我们上一次讨论了输入函数,我看到作为输入键入的任何内容都存储为字符串。您可以在输入函数之前使用int()和float()来存储为数字,但我想知道如何使用它来存储用户输入的函数。有没有一种方法可以使用输入来定义函数?您可以使用exec()内置函数来实现这一点 更多参考:一个潜在的解决方案是允许用户按名称调用预定义的方法。这比直接使用exec()命令更安全,因为它严格限制了用户触发代码块的能力 def SomeAction(): print("SomeActi

在我的python入门课程中,我们上一次讨论了输入函数,我看到作为输入键入的任何内容都存储为字符串。您可以在输入函数之前使用int()和float()来存储为数字,但我想知道如何使用它来存储用户输入的函数。有没有一种方法可以使用输入来定义函数?

您可以使用
exec()
内置函数来实现这一点


更多参考:

一个潜在的解决方案是允许用户按名称调用预定义的方法。这比直接使用
exec()
命令更安全,因为它严格限制了用户触发代码块的能力

def SomeAction():
    print("SomeAction has been executed.")

userInput = input("Enter method name: ")
if(userInput == SomeAction.__name__):
    method = getattr(sys.modules[__name__], SomeAction.__name__)  #Get method by name
    method()
但是,如果要让用户完全从
input
调用定义方法,则需要创建
input
循环以获取方法体

print("Enter your method declaration: ")
methodDeclaration = ""
methodLine = "X"
i = 1
while(len(methodLine) != 0):
    methodLine = input(str(i) + ": ")
    i = i+1
    methodDeclaration = methodDeclaration +"\n"+ methodLine

print("Method to be executed:")
print(methodDeclaration)

exec(methodDeclaration)
myMethod()
上述代码的输出如下:

Enter method name: SomeAction
SomeAction has been executed.


Enter your method declaration: 

1: def myMethod():

2:  print("MyMethod is running!")

3: 
Method to be executed:

def myMethod():
        print("MyMethod is running!")

MyMethod is running!

请注意,这不是一种安全的做法。使用
exec()
允许用户在python脚本中输入任何所需的命令。尽管如此,从输入中使用用户定义的方法确实是可能的。

欢迎!我想你会从这篇文章中受益:这几乎总是一个坏主意——如果你在写输入,那么你可以很容易地编辑源代码。如果另一个“用户”正在编写输入,那么他们很容易编写恶意代码,然后您将执行这些代码。我建议对字符串输入进行仔细分析,只验证所需的输入类型
print("Enter your method declaration: ")
methodDeclaration = ""
methodLine = "X"
i = 1
while(len(methodLine) != 0):
    methodLine = input(str(i) + ": ")
    i = i+1
    methodDeclaration = methodDeclaration +"\n"+ methodLine

print("Method to be executed:")
print(methodDeclaration)

exec(methodDeclaration)
myMethod()
Enter method name: SomeAction
SomeAction has been executed.


Enter your method declaration: 

1: def myMethod():

2:  print("MyMethod is running!")

3: 
Method to be executed:

def myMethod():
        print("MyMethod is running!")

MyMethod is running!