【问题标题】:Importing files from different directory从不同目录导入文件
【发布时间】:2020-09-10 21:43:45
【问题描述】:

我有以下文件夹结构:

Python_Game/src/domain/boards.py
Python_Game/tests/test.py

我正在尝试将函数 board.py 导入 test.py。

我试过了:

import sys
sys.path.append('../src')
import domain
from domain import boards

还有很多其他尝试(也包括 StackOverflow 中的提示),但到目前为止我无法正确导入。请给我一些建议。

我正在使用 Python 3.7.4,域和测试文件夹包含 __init__.py 文件。

【问题讨论】:

  • 您是否尝试过使用import ..src.domain.boards

标签: python python-3.x import python-import


【解决方案1】:

从您的 src 目录:

import domain.boards as boards

从您的 Python_Game 目录:

import src.domain.boards as boards

并遵循相同的测试逻辑

【讨论】:

  • 但是当我尝试从 test.py 文件中导入板时,我首先需要转到父目录...我认为这就是为什么此选项对于测试目录无法正常工作
【解决方案2】:

从测试中访问板:

import sys
#use full path for your boards file; if you are on windows replace / with \\
sys.path.append('Python_Game/src/domain/boards.py')

#import entire module:
import boards as boards

#or import specific functions/variables
from boards import function_name

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    相关资源
    最近更新 更多