如何从python中的父文件夹导入函数?

Den*_*nko 3 python python-import python-3.x

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

我知道关于 SO 有很多类似的问题,但是,不幸的是,我找不到适合我的解决方案,因为答案要么过于具体,要么过于笼统,或者它们只是丑陋的黑客(例如操作使用绝对路径)。

这是我的文件夹结构的样子:

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
Run Code Online (Sandbox Code Playgroud)

我需要./hashes/hash_function.py./diffie_hellman/diffie_hellman.py.

./hashes/hash_function.py文件包含唯一名为hash_function.

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

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

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

或者我得到这个:

导入错误:没有名为“哈希”的模块

每个__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/

Caf*_*led 6

I know you have already accepted an answer, but if you wanted a less "permanent" solution (that is to say, if you didn't want to install your code), another option would be to simply add the parent of your PythonClient directory to your path. This can be done permanently (which varies depending upon operating system) or temporarily in code:

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
Run Code Online (Sandbox Code Playgroud)

Cheers!


Tom*_*mmy 3

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

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