【问题标题】:How to import a function from parent folder in python?如何从python中的父文件夹导入函数?
【发布时间】:2016-08-05 22:52:21
【问题描述】:

我需要在我的 python 项目上执行一个函数的导入。

我知道关于 SO 有许多类似的问题,但是,不幸的是,我找不到适合我的解决方案,因为答案要么过于具体,要么过于笼统,要么只是丑陋的 hack (就像使用绝对路径操作一样)。

我的文件夹结构如下所示:

PythonClient:.
│   .gitignore
│   des.py
│   des_test.py
│   des_var2.py
│   gui.py
│   index.py
│   __init__.py
│
├───diffie_hellman
│   │   diffie_hellman.py
│   │   diffie_hellman_test.py
│   │   __init__.py
│   │
│   └───__pycache__
│           diffie_hellman.cpython-35.pyc
│
├───hashes
│   │   collision.py
│   │   hash_function.py
│   │   __init__.py
│   │
│   └───__pycache__
│           hash_function.cpython-35.pyc
│           __init__.cpython-35.pyc
│
└───__pycache__
        des.cpython-35.pyc
        des_var2.cpython-35.pyc

我需要从./diffie_hellman/diffie_hellman.py 导入./hashes/hash_function.py。

./hashes/hash_function.py 文件包含唯一名为 hash_function 的函数。

我已经尝试了很多方法来执行导入,但就是无法做到。 我总是得到任何一个

SystemError: 父模块''未加载,无法执行相对 进口

当我在导入语句中使用. 时(即from .hashes.hash_function)

或者我明白了:

ImportError: 没有名为“哈希”的模块

每个__init__.py 文件都是空的。

这是我的尝试列表:

  1. from hashes import hash_function

  2. from hashes.hash_function import hash_function

  3. from .hashes.hash_function import hash_function

  4. from ..hashes.hash_function import hash_function

  5. import hashes

  6. import hash_function

  7. from .. import hash_function

  8. from . import hash_function

  9. from PythonClient.hashes.hash_function import hash_function


您能帮我解决我的问题并了解如何使用此类导入吗?


PS:这里找不到解决方案stackoverflow.com/questions/14132789/

【问题讨论】:

标签: python python-3.x python-import


【解决方案1】:

我知道您已经接受了答案,但如果您想要一个不那么“永久”的解决方案(也就是说,如果您不想安装您的代码),另一种选择是只需将您的 PythonClient 目录的父级添加到您的路径。这可以永久完成(取决于操作系统)或暂时在代码中完成:

import os
import sys

p = os.path.abspath('../..')
if p not in sys.path:
    sys.path.append(p)

from PythonClient.hashes.hash_function import hash_function

干杯!

【讨论】:

    【解决方案2】:

    你有一个__init__.py 的事实告诉我 PythonClient 本身就是一个库。做from PythonClient.hashes.hash_function import hash_function。我总是喜欢完全合格的路径。

    您还需要安装您的库,然后才能从中导入。这需要您的主目录中的 setup.py 文件。之后,您应该 pip install 库进行测试,例如,`pip install -e 。

    【讨论】:

    • 我的根文件夹名为PythonClient。但是当我做from PythonClient.hashes.hash_function import hash_function 我得到ImportError: No module named 'PythonClient'
    • 它给了我Directory '.' is not installable. File 'setup.py' not found.。如果我必须创建setup.py 文件,它应该是什么样的,应该放在哪里?
    • 谢谢,创建setup.py 解决了这个问题!请您更新您的答案,以便我可以将其标记为已回答,以便其他人可以看到它?
    猜你喜欢
    • 2022-11-17
    • 1970-01-01
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    相关资源
    最近更新 更多