【问题标题】:How to execute a function inside a python script on a string [closed]如何在字符串上的python脚本中执行函数[关闭]
【发布时间】:2021-02-21 05:11:03
【问题描述】:

我在通过 API 获得的 Python 字符串中有以下脚本:

script = """
import logging        
    
def run():
    logging.info('Function Executed')
    return "SUCCESS"
"""

我需要的是运行该脚本的run 函数并在Python 中检索它的返回值。 我用evalexec 尝试了这种方式,但没有成功:

eval:

script = """
import logging        
    
def run():
    logging.info('Function Executed')
    return "SUCCESS"
"""

response = eval(script).run()

exec:

script = """
import logging        
    
def run():
    logging.info('Function Executed')
    return "SUCCESS"
"""

exec script
response = run()

注意:我需要在请求上下文中执行此操作,这样run 方法就不会并发执行。

更新: 注意:这是一个特定的内部用例,它不会是一个暴露在互联网上的 API。该用例用于用 Python 编写的反欺诈规则引擎。规则由分析师编写,并以我在问题中编写的格式存储在数据库中。引擎的提议是寻找并执行这些用 Python 编写的规则。

【问题讨论】:

  • that I get through API ...这听起来像是主要脚本注入攻击的潜在来源。为什么要运行从 API 端点接收的 Python 代码?
  • 从安全的角度来看,这是一个非常糟糕的主意。您应该自动执行从 API 获得的代码。
  • 这是一个特定的内部用例,它不会是一个暴露在互联网上的 API。该用例用于用 Python 编写的反欺诈规则引擎。规则由分析师编写,并以我在问题中编写的格式存储在数据库中。引擎的作用就是寻找并执行这些用 Python 编写的规则。

标签: python python-3.x


【解决方案1】:

首先,从安全角度来看,这样做并不是一个好主意。

但是,如果你想这样做,你可以这样做:

import os

script = """
print("Executed!")
"""

with open('script.py','w') as fhand:
    fhand.write(script)

os.system('python script.py')

您可以将script 中的字符串写入另一个*.py 文件,然后运行该脚本。

编辑: 如果你想执行这个函数,你可以这样做:

import os

scriipt = """
def hello():
    print('Executed')
"""

with open('script.py','w') as fhand:
    fhand.write(scriipt)

import script  //which is the name of the python file

script.hello()

一个缺点,你应该知道函数的名称。

【讨论】:

  • Mayank,如何在每个请求的隔离上下文中执行此文件中的函数?
  • @JoãoRafaelCamposdaSilva 更新了答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 2011-11-13
  • 2020-05-23
  • 2011-03-31
  • 2019-12-18
  • 2021-07-28
  • 1970-01-01
相关资源
最近更新 更多