简体   繁体   English

Python检查字符串是否在dir()中,以及是否将该字符串转换为方法/函数调用

[英]Python check if a string is in dir() and if it is convert that string into a method/function call

How do I turn a user generated string into a method or function call in Python2.7? 如何在Python2.7中将用户生成的字符串转换为方法或函数调用? Can you search the dir(object) to see if the method/function exists and then call that method? 您可以搜索目录(对象)以查看方法/函数是否存在,然后调用该方法吗?

It is best to just try to call the method, if it's not there it will throw an exception, which you can handle. 最好只是尝试调用该方法,如果不存在,它将抛出一个异常,您可以处理该异常。

>>> try: obj.a_method()
... except AttributeError: print 'No method a_method in this object'
... 
No method a_method in this object
>>> 

You could try something like: 您可以尝试类似:

ui = input("Try something: ")
if ui in dir():
    func = eval(ui)
    func()

For example: 例如:

>>> def test():
    return "foo"

>>> if "test" in dir():
    func = eval("test")
    func()


'foo'

Function names are just attributes, so you can do this: 函数名称只是属性,因此您可以执行以下操作:

try:
    getattr(object, methodname)()
except AttributeError as e:
    print 'Method %s not found or not callable!'%methodname

You can use globals it returns module's __dict__ 您可以使用它返回模块的__dict__ globals

def command_1():                                                                
    print "You are in command 1"                                                

def command_2():                                                                
    print "You are in command 2"                                                

def default():                                                                  
    print "Can't find your command"                                             

func = raw_input("ENTER YOUR COMMAND: ")                                        
your_func = globals().get(func, None)                                           
if your_func is None:                                                                                                                                       
    your_func = default                                                         

your_func() 

Output: 输出:

ENTER YOUR COMMAND: command_1
You are in command 1

or 要么

ENTER YOUR COMMAND: aaa
Can't find your command

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM