【问题标题】:How to find which function became from "from - import" module如何查找哪个函数来自“从-导入”模块
【发布时间】:2021-02-11 14:18:24
【问题描述】:

我对“从 - 导入”功能有疑问。例如。我有 3 个文件:one.py、two.py、three.py。

three.py文件内容:

from one import *
from two import *


variable1
variable2

def func1()

def func2()

def func3()

假设我没有以上两个文件的权限,我无法打开它们。我的问题是,如何检查 one.py 或 two.py 文件中的哪个函数和哪个变量?有什么命令之类的吗?

【问题讨论】:

  • 你检查过dir(one),以防你使用import one。如果您使用from one import *,那么只需使用dir()

标签: python import module libraries python-importlib


【解决方案1】:

您可以使用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

【讨论】:

    【解决方案2】:
    print(func1.__module__)
    print(func2.__module__)
    print(func3.__module__)
    

    【讨论】:

      【解决方案3】:

      您可以将 try-except 应用于 import 语句。

      try:
        from one import *
        from two import *
      except ImportError:
        # Override variables after failed import
        var1 = ...
        var2 = ...
      

      【讨论】:

        【解决方案4】:

        您可以使用模块的命名空间调用函数\变量

        并使用 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)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-12-04
          • 2011-04-10
          • 1970-01-01
          • 1970-01-01
          • 2021-02-18
          • 2021-08-31
          • 2011-04-06
          • 2011-10-09
          相关资源
          最近更新 更多