我需要在我的python项目上执行一个函数的导入。如何在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
我需要从./diffie_hellman/diffie_hellman.py
导入./hashes/hash_function.py
。
./hashes/hash_function.py
文件包含唯一名为hash_function
的函数。
我已经尝试了很多方法来执行导入,但不能做到这一点。 我总是要么
SystemError: Parent module '' not loaded, cannot perform relative import
,当我在我的import语句(即from .hashes.hash_function
)
使用.
或我得到这个:
ImportError: No module named 'hashes'
每个__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/
我建议你先阅读http://stackoverflow.com/questions/14132789/python-relative-imports-for-the-billionth-time#answer-14132912。如果仔细阅读,可以解决99%的python导入问题。 – laike9m