如何在Python函数中使用exec(“import xxx”)中的模块?(How to make modules from exec(“import xxx”) in a Python functi

编程入门 行业动态 更新时间:2024-10-26 22:25:43
如何在Python函数中使用exec(“import xxx”)中的模块?(How to make modules from exec(“import xxx”) in a Python function available?)

我自己写了一个简单的函数,通过我的Python文件夹筛选并查找可能的模块的位置。 我想要做的事很简单。 我传递一个模块导入的字符串,该函数将找到该模块的文件夹,cd在那里,并将其导入到我工作的任何环境中,例如:

anyimport('from fun_abc import *')

注意:

除了@Nayya的点滴答案,你必须通过范围来使exec工作,为了避免“ImportError”,你需要在运行exec之前添加这行:

sys.path.append(os.path.join(os.path.dirname(__file__), pointdir)) exec (evalstr, scope)

Attention:

In addition to @Noya's spot-on answer that one has to pass the scope to make the exec work, to avoid "ImportError", you need to add this line before running exec:

sys.path.append(os.path.join(os.path.dirname(__file__), pointdir)) exec (evalstr, scope)

This is due to the reason that our modification of sys.path assumes the current working directory is always in main/. We need to add the parent directory to sys.path. See this Stack Overflow discussion "ImportError: No module named - Python" for more information on resolving this issue.

最满意答案

exec执行当前范围内的代码。 在函数内部,这意味着(函数)本地范围。

你可以通过给它一个元组(code, scope)来告诉exec把变量放到另一个范围中。 例如,您可以使用globals()在模块级别提供名称。

请注意, 全局变量

总是当前模块的字典(在一个函数或方法中,这是它被定义的模块,而不是它被调用的模块)。

因此,在你的例子中,你必须将期望的范围传递给你的效用函数:

anyimport.py

class anyimport(object): def __init__(self, importmodule, scope): exec (importmodule, scope)

test.py

a = 42 b = 'foo'

main.py

from anyimport import anyimport if __name__ == '__main__': anyimport('from test import *', globals()) # 42 foo print a, b

用python main.py测试它。 确保所有文件都存在于当前目录中。

替代方案

如果你不想使用exec ,更好的方法是使用Python提供的导入工具。

以下内容取自https://stackoverflow.com/a/4526709/453074 , from some.package import *等效:

[...]用户importlib更方便:

globals().update(importlib.import_module('some.package').__dict__)

exec executes code in the current scope. Inside a function, this means the (function-) local scope.

You can tell exec to put variables in another scope by giving it a tuple (code, scope). For example, you can use globals() to make names available at the module level.

Be aware, that globals

is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).

Thus, in your example, you have to pass the desired scope to your utility function:

anyimport.py:

class anyimport(object): def __init__(self, importmodule, scope): exec (importmodule, scope)

test.py:

a = 42 b = 'foo'

main.py:

from anyimport import anyimport if __name__ == '__main__': anyimport('from test import *', globals()) # 42 foo print a, b

Test it with python main.py. Make sure all files are present in the current directory.

Alternative Solution

If you are not bound to use exec, a more elegant way would be to use the import utilities provided by Python.

The following, taken from https://stackoverflow.com/a/4526709/453074 , is equivalent to from some.package import *:

[...] it's more convenient to user importlib:

globals().update(importlib.import_module('some.package').__dict__)

.

更多推荐

本文发布于:2023-08-07 20:49:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465640.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   模块   如何在   Python   import

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!