如何正确使用python的导入函数__import __() [英] How to use python's import function properly __import__()

查看:595
本文介绍了如何正确使用python的导入函数__import __()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 __ import __ 函数从foo.bar导入对象复制,我似乎有撞墙。

I'm trying to replicate from foo.bar import object using the __import__ function and I seem to have hit a wall.

来自glob import glob 很简单:
glob = __import __(glob,glob) glob = __import __(glob)。glob

我遇到的问题是我从包中导入(即bar),我希望包中的脚本成为导入源。

The problem I'm having is that I am importing from a package (i.e. bar) and I want the script in the package to be the source of the import.

所以我想要的是

string_to_import = "bar"
object = __import__("foo",string_to_import).object

但这只是导入 __ init __ 在foo包中。

But this just imports the __init__ in the foo package.

如何做到这一点?

编辑:
当我使用显而易见的东西时,只调用 __ init __

__import__("foo.bar")
<module 'foo' from 'foo/__init__.pyc'>


推荐答案

import语句将返回a的顶级模块包,除非您传递以下附加参数。

The import statement will return the top level module of a package, unless you pass the following additional arguments.

_temp = __import__('foo.bar', globals(), locals(), ['object'], -1) 
object = _temp.object

请参阅 __ import __ 声明

这篇关于如何正确使用python的导入函数__import __()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆