如何解决如何找到哪个函数来自“from - import”模块
我对“from - import”功能有疑问。例如。我有 3 个文件:one.py、two.py、three.py。
from one import *
from two import *
variable1
variable2
def func1()
def func2()
def func3()
比方说,我没有以上两个文件的权限,我无法打开它们。我的问题是,如何检查哪个函数和哪个变量来自 one.py 或 two.py 文件?有什么命令之类的吗?
解决方法
您可以使用 getfile
模块中的 inspect
Return the name of the (text or binary) file in which an object was defined. This will fail with a TypeError if the object is a built-in module,class,or function.
https://docs.python.org/3/library/inspect.html#inspect.getfile
,print(func1.__module__)
print(func2.__module__)
print(func3.__module__)
,
您可以将 try-except 应用于导入语句。
try:
from one import *
from two import *
except ImportError:
# Override variables after failed import
var1 = ...
var2 = ...
,
可以使用模块的命名空间调用函数\变量
并使用 try/ 进行检查,但在导入模块时不会出现错误
try:
from one
one.foo()
one.variable1
except ImportError as exception:
print(exception)
try:
from two
two.foo()
two.variable1
except ImportError as exception:
print(exception)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。