我需要在我的 python 项目上执行函数的导入。
我知道有很多类似的问题,但是,不幸的是,我找不到适合我的解决方案,因为答案要么太具体,要么太笼统,要么它们只是丑陋的黑客(比如操作与绝对路径)。
我的文件夹结构如下所示:
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
我需要导入./hashes/hash_function.py
from ./diffie_hellman/diffie_hellman.py
.
The ./hashes/hash_function.py
文件包含唯一名为的函数hash_function
.
我尝试了很多方法来执行导入,但就是无法做到。
我总是得到
系统错误:父模块“”未加载,无法执行相对
进口
当我使用.
在我的导入声明中(即from .hashes.hash_function
)
或者我得到这个:
导入错误:没有名为“哈希”的模块
Every __init__.py
文件为空。
这是我的尝试列表:
from hashes import hash_function
from hashes.hash_function import hash_function
from .hashes.hash_function import hash_function
from ..hashes.hash_function import hash_function
import hashes
import hash_function
from .. import hash_function
from . import hash_function
from PythonClient.hashes.hash_function import hash_function
您能否帮助我解决我的问题并了解如何使用此类导入?
PS:这里找不到解决方案stackoverflow.com/questions/14132789/
我知道您已经接受了答案,但是如果您想要一个不太“永久”的解决方案(也就是说,如果您不想install您的代码),另一个选择是简单地将 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
Cheers!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)