Python——如何优雅的导入自定义的Python包


对于IDEA的管理

  • 在IDEA中运行文件时,当前项目根目录会默认被添加为Python的搜索路径
  • 根目录下的文件可以直接被访问
  • 根目录的子目录需要每一层都添加__init__.py文件,将其编译为包

IDEA项目用命令行运行

  • 在运行的第一个文件中添加IDEA项目的根目录作为搜索路径

    • 这里的根目录最好是绝对路径
      1
      2
      import sys
      sys.path.append("/home/xxx/xxx/xxx")
  • 如果是想使用相对路径,从而方便移植也行,但需要获取当前文件的文件路径,然后从当前文件与根目录的关系解析出根目录

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    import os
    thisFileDir = os.path.split(os.path.realpath(__file__))[0]
    # we have to modify the tail if we change the path of this python file
    tail = 6
    rootPath = thisFileDir[0:-tail]
    if rootPath[-1] != "/" and rootPath[-1] != "\\":
    message = "Error root path [%s]\n\tPlease check whether you changed the path of current file" % rootPath
    raise Exception(message)
    print "Current root path: %s" % rootPath

    import sys
    sys.path.append(rootPath)
  • 其他的和在IDEA中运行一样,需要添加的库加上__init__.py即可