[英]Pros and cons of using exec for importing a specific module?
I would like to find out disadvantages of using exec
for imports. 我想找出使用exec
进行导入的缺点。 One of the files serves as interface towards real implementations of specific functionalities depending on chosen project (framework is intended to work on several projects). 其中一个文件用作特定功能的实际实现的接口,具体取决于所选择的项目(框架旨在用于多个项目)。
First use-case goes like this: 第一个用例是这样的:
exec ("from API.%s.specific_API_%s import *" % (project, project))
This way I don't have to hard code anything except the variable project
which is injected in the interface-module itself. 这样,除了注入接口模块本身的变量project
外,我无需进行任何硬编码。
This is the other way: 这是另一种方式:
if project == 'project_one':
from API.project_one.specific_API_project_one import *
elif project == 'project_two':
from API.project_two.specific_API_project_two import *
elif project == 'project_three':
from API.project_three.specific_API_project_three import *
This way I have to alter this interface-file each time new project is added to be supported. 这样,每次添加新项目来支持时,我都必须更改此接口文件。
importlib
or __import__
(for really specific cases). 如果您需要以编程方式导入模块,请使用importlib
或__import__
(针对特定情况)。 Reasons — don't re-invent the wheel, there's way to do what you want without exec
. 原因-不要重新发明轮子,如果没有exec
,就有办法做自己想做的事情。 If your project
variable coming from outer world, exec
is a huge security issue. 如果您的project
变量来自外部世界,则exec
是一个巨大的安全问题。 Oversimplified example of issues with exec
by executing arbitrary code: 通过执行任意代码, exec
问题的过于简化的示例:
module = 'request'
func = 'urlopen'
exec("from urllib.%s import %s" % (module, func))
func = 'urlopen; print("hello python")'
exec("from urllib.%s import %s" % (module, func))
yes, your example is harder to forge, but problem stays — giving python arbitrary code to execute is overkill (with potential security gap), when you have tool built exactly for your purpose — programatically importing modules. 是的,您的示例更难伪造,但问题依然存在-当您完全根据目的构建了工具时,给python任意代码执行代码是过高的(有潜在的安全漏洞)-以编程方式导入模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.