简体   繁体   中英

How do you convert a string to a function in python?

如何将字符串(例如,来自文本框的输入)转换为适当的函数?

You can use eval . But be very careful! This opens up lots of security holes.

>>> s = '3+4'
>>> eval(s)
7

If you want it callable:

>>> s = '3+4'
>>> f = eval('lambda: ' + s)
>>> f()
7

More information on eval here .

try this

func = ___import___('func_name')

or

if hasattr(your_module, func_name): func = getattr(your_module, func_name)

or

if func_name in globals(): func = globals[func_name]

or something etc

def func():
    print "hello"

# just eval it
eval(raw_input())

# if you just want to ask for name
fName=raw_input()
if fName in globals():
    globals()[fName]()

And there could be various other ways depending on what is the objective?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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