Python 提供了几种方法来执行它自己的代码。通常有两个Built-in Functions可以让我们从python内部执行python代码-:
-
eval function -: eval 函数可用于执行您需要的任何表达式,但请注意,使用 eval 无法执行多行 python 代码。
-
exec function -: exec 函数也可用于动态执行多行 python 代码。因此,它不同于 eval 函数,因为它能够执行的不仅仅是 python 表达式。
现在对于您的用例,因为您只想执行存储在字符串中的 python 表达式,可以说e,可以执行以下操作 -:
e = '(2 *(4 - 3)) * 2' # Note that the previously written expression [2(4 - 3) * 2 is not a valid python expression as pointed out by @Brendan Abel]
result = eval(e) # The eval function executes the expression e and the result is stored in the result variable.
编辑:因此,在您发表评论后,您似乎需要将其转换为可供您使用并且可以随时运行的正常表达式。
同样,我们可以创建一个名为 Expression 的类,然后我们可以让它将表达式存储为 .py 文件。
该类的表达式对象可以随时运行,也可以在最后处理删除最初创建的.py文件。
相同的代码看起来像这样 -:
import importlib # Used for the Expression.run method.
import os # Used for the Expression.dispose method.
class Expression() :
def __init__(self, expr_name, str_expr) :
# This function is called at initialization of an Expression object.
self.expr_name = expr_name
self.str_expr = str_expr
self.module_obj = None # To store the module object returned by the import_module function.(defaultly None)
self.store() # Saves the expression as a .py file.
return
def store(self) :
# Creates a .py file with the name as that of the expression name to store
# the string expression for it to be later executed.
addr = self.expr_name + '.py'
with open(addr, 'w') as f :
f.write(self.str_expr)
return
def dispose(self) :
# Should be called either at the end of the program or whenever the use
# for the expression has ended and no further use is needed, this function
# deletes the .py file created initially to store the expression.
addr = self.expr_name + '.py'
os.remove(addr)
return
def run(self) :
# This function can be called to execute the expression and it imports
# the .py file previously created to indirectly execute it.
if self.module_obj == None :
# If the module_obj value is None it means the module is being
# imported for the first time.
self.module_obj = importlib.import_module(self.expr_name)
else :
# If the module_obj value is not None then the module has been
# imported before and thus is now reloaded using the previously
# stored module object.
self.module_obj = importlib.reload(self.module_obj)
return
pass
# The string expression.
e = 'print((2 * (4 - 3)) * 2)'
# Creating an expression object.
e_ = Expression('e1', e)
# Will print the result three times
e_.run()
e_.run()
e_.run()
# Now we dispose the expression since it is not needed anymore.
e_.dispose()
同样的输出是-:
4
4
4
程序执行完毕后,如果使用的表达式已经被释放,所有使用的.py表达式文件都将被删除。