Skip to main content
 首页 » 编程设计

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

2025年05月04日30xiaohuochai

我需要在我的 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

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

或者我明白了:

ImportError: No module named 'hashes'

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

这是我的尝试列表:

  1. from hashes import hash_function

  2. from hashes.hash_function import hash_function

  3. 从.hashes.hash_function import hash_function

  4. 从 ..hashes.hash_function 导入 hash_function

  5. 导入哈希

  6. 导入哈希函数

  7. from .. import hash_function

  8. 来自 .导入哈希函数

  9. 从 PythonClient.hashes.hash_function 导入 hash_function


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


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

请您参考如下方法:

我知道你已经接受了一个答案,但如果你想要一个不太“永久”的解决方案(也就是说,如果你不想安装你的代码),另一种选择是是简单地将 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 

干杯!