我有关于"from - import"函数。例如,我有3个文件:one.py, two.py, three.py.
three.py文件内容:
from one import *
from two import *
variable1
variable2
def func1()
def func2()
def func3()
假设我没有上述两个文件的权限,我无法打开它们。我的问题是,如何检查哪个函数和哪个变量成为从一个。py或两个。py文件?有什么命令之类的吗?
您可以使用inspect
模块中的getfile
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__)
您可以对import语句应用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)