【问题标题】:Importing my own python module [duplicate]导入我自己的 python 模块 [重复]
【发布时间】:2018-06-21 13:00:36
【问题描述】:

我可以像 os, sys 模块一样导入 test01.py 吗?

我想导入test01.py like:

import test01.py

在这种情况下,我只能这样导入:

from testDemo02 import test01

有可能到达吗?

【问题讨论】:

  • 你试过import test01吗?还是我错过了什么?

标签: python


【解决方案1】:

看起来test01 在包testDemo02 中 - 你可以知道,因为在目录testDemo02 中有一个文件__init__.py。鉴于此,有两种可能性:

  • 如果testDemo02父目录在模块搜索路径(sys.path)中,但testDemo02 本身不在,您可以使用任一方式导入您的test01 模块

    import testDemo02.test01
    

    from testDemo02 import test01
    

    我怀疑是这种情况,因为您尝试了后一种并且它有效。这是我所期望的,因为我在那里看到了 __init__.py 文件。

  • 如果testDemo02 本身在搜索路径中,您将能够只导入您的模块

    import test01
    

    当目录还包含__init__.py 文件时,我会觉得搜索路径中的目录很奇怪,但这是可能的。

【讨论】:

    【解决方案2】:

    您可以使用sys 模块的路径属性来附加您的路径:

    >>> import sys
    >>> sys.path.append("/testDemo02/test01")
    >>> import test01
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-12
      • 1970-01-01
      • 2021-05-18
      • 1970-01-01
      • 2015-10-19
      • 2020-01-10
      • 2015-11-11
      • 1970-01-01
      相关资源
      最近更新 更多