简体   繁体   English

从测试子目录导入python项目模块

[英]Import python project modules from tests subdirectory

├── ledger
│   ├── __init__.py
│   ├── ledger_data.py
│   └── ledger_model.py
├── main.py
├── sscommon
│   ├── __init__.py
│   └── logging.py
└── tests
    └── test_ledger_data.py

I need to import classes from ledger_data module when running test_ledger_data.py . 运行test_ledger_data.py时,我需要从ledger_data模块导入类。 I currently do sys.path.append("../") in test_ledger_data.py or I have to add symbolik links to all modules being used to tests directory. 我目前在test_ledger_data.py执行sys.path.append("../") ,或者我必须向用于tests目录的所有模块添加symbolik链接。 Both options seem incorrect. 这两个选项似乎都不正确。 How to do it correctly? 如何正确做?

If I just run the file either from project root or tests directories I get error: 如果我只是从项目根目录或tests目录运行文件,则会收到错误消息:

    from ledger.ledger_data import LedgerData
ImportError: No module named 'ledger'

You can create an __init__.py file in your folder, and import the parent dir using: 您可以在文件夹中创建__init__.py文件,并使用以下命令导入父目录:

parent_dir = os.path.abspath(os.path.join(os.path.abspath(__file__), os.pardir))
sys.append(parent_dir)

This uses os.path to find out the directory based on your file location. 这使用os.path根据您的文件位置查找目录。


Update : create the above __init__.py and reside it inside tests/ folder. 更新 :创建上面的__init__.py并将其驻留在tests/文件夹中。 Then, in your test_ledge_data.py put at the head of the file from __init__ import * ; 然后,在您的test_ledge_data.py中, from __init__ import *放到文件的开头; this will import everything in your init file to your module namespace. 这会将init文件中的所有内容导入模块名称空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM