【问题标题】:How to import a python file in a parent directory如何在父目录中导入python文件
【发布时间】:2012-04-22 03:01:12
【问题描述】:

如果我有以下目录结构:

parent/
    - __init__.py
    - file1.py
    - child/
        - __init__.py
        - file2.py

在文件 2 中,我将如何导入文件 1?

更新

>>> import sys
>>> sys.path.append(sys.path.append('/'.join(os.getcwd().split('/')[:-2])))
>>> import parent
>>> ImportError: No module named parent

【问题讨论】:

    标签: python


    【解决方案1】:

    您仍然需要提及父级,因为它们位于不同的命名空间中:

    import parent.file1
    

    【讨论】:

    • 即使我提到父母,我仍然会遇到同样的导入错误。
    • @David542 显然,父目录需要在 sys.path 中。
    • @Jiri 我试过这个[见上面的修订问题],但似乎仍然遇到同样的问题。
    • @David542 尝试改用sys.path.append('/Users/Premiere_032/Desktop')
    • @David542 您的 init.py 文件命名错误。它不应该以下划线结尾!正确:_ _ i n i t _ _ 。 y
    【解决方案2】:

    您需要指定父级,并且它需要在 sys.path 上

    import sys
    sys.path.append(path_to_parent)
    import parent.file1
    

    【讨论】:

    • 我试过这个 [参见上面的修订问题],但似乎仍然遇到同样的问题。
    • 这是你的树形结构中的错字吗,你需要__init__.py,而不是__.init__.py
    • -1:在这种情况下不应使用 sys.path hacks。普通的绝对/相对导入就够了
    【解决方案3】:

    在 Python 文档中有一个完整的关于模块的部分:

    Python 2: http://docs.python.org/tutorial/modules.html

    Python 3: http://docs.python.org/py3k/tutorial/modules.html

    关于父包(以及其他)的具体导入,请参见第 6.4.2 节

    【讨论】:

      【解决方案4】:

      这是我用来导入任何东西的东西。当然,你还是得把这个脚本复制到本地目录,导入,use你想要的路径。

      import sys
      import os
      
      # a function that can be used to import a python module from anywhere - even parent directories
      def use(path):
          scriptDirectory = os.path.dirname(sys.argv[0])  # this is necessary to allow drag and drop (over the script) to work
          importPath = os.path.dirname(path)
          importModule = os.path.basename(path)
          sys.path.append(scriptDirectory+"\\"+importPath)        # Effing mess you have to go through to get python to import from a parent directory
      
          module = __import__(importModule)
          for attr in dir(module):
              if not attr.startswith('_'):
                  __builtins__[attr] = getattr(module, attr)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-17
        • 1970-01-01
        • 2018-10-09
        • 2021-09-08
        • 2013-05-22
        • 1970-01-01
        • 1970-01-01
        • 2013-11-09
        相关资源
        最近更新 更多