简体   繁体   English

使用python 2.7从并行目录导入

[英]Importing from parallel directories with python 2.7

I have recently started working on a project and have been tasked with implementing some new features as well as unit testing for those features. 我最近开始从事一个项目,并负责实现一些新功能以及这些功能的单元测试。 I have been trying to import modules into the unit testing file but when I run it I come across an ImportError: No module named Developing.algorithms when I try to import into test_algorithms.py 我一直在尝试将模块导入单元测试文件,但是当我运行它时,我遇到一个ImportError:当我尝试导入到test_algorithms.py时没有名为Development.algorithms的模块

I have tried importing with both 我尝试了两者都导入

from Developing import algorithms as algo

and

import Developing.algorithms as algo

My structure is similar to this Testing project that I made: 我的结构类似于我所做的此测试项目:

Testing/
    __init__.py
    Developing/
        __init__.py
        algorithms.py
    Master (Stable)/
    Tests/
        __init__.py
        test_algorithms.py

And I run into: 我遇到了:

ImportError: No module named Developing.algorithms

Or when I change the import to: from Developing import algorithms 或将导入更改为:从开发导入算法

ImportError: No module named Developing

I have read many similar questions and from those I have learned to include init .py files into each directory that has a file that I want to import. 我已经阅读了许多类似的问题,并且从中学到的问题中,我将init .py文件包含在每个具有要导入的文件的目录中。 I currently do not have any errors according to PyCharm but when I run it from terminal I run into that import error. 根据PyCharm,我目前没有任何错误,但是当我从终端运行它时,遇到了导入错误。 I also do not want to modify the system / python path as I read that everyone that uses the project would have to so the same. 我也不想修改system / python路径,因为我读到使用该项目的每个人都必须如此。 So how can I import from parallel directories without changing paths? 那么如何在不更改路径的情况下从并行目录导入?

You will need to add the directory Testing into your PYTHONPATH env variable, to be able to import Developing.algorithms directly (or the directory above Testing to be able to import Testing.Developing.algorithms ). 您需要的目录添加Testing到您的PYTHONPATH环境变量,要能够导入Developing.algorithms直接(或以上的目录Testing ,以便能够导入Testing.Developing.algorithms )。

In windows, you can set the PYTHONPATH variable as - 在Windows中,您可以将PYTHONPATH变量设置为-

set PYTHONPATH=\path\to\Testing\;%PYTHONPATH%

In Bash , you can try - 在Bash中,您可以尝试-

export PYTHONPATH=/path/to/testing/:$PYTHONPATH

Programatically (from python) , you can do the following before you try to import Developing.algorithms - 以编程方式(从python),您可以在尝试导入Developing.algorithms之前执行以下操作-

import sys
sys.path.append('/path/to/Testing/')
from Developing import algorithms # or how ever you want to import.

Also, you do not need to do all of the above, any one would do - either setting PYTHONPATH env variable, or using sys.path . 另外,您不需要执行以上所有操作,任何一个都可以-设置PYTHONPATH env变量,或使用sys.path

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

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