简体   繁体   English

Python 在目录中导入

[英]Python imports within a directory

I have a project that is structured thus:我有一个结构如下的项目:

.
  |-dir
  |  |-subdir
  |  |  |-subsubdir1
  |  |  |-subsubdir2
  |  |  |-subsubdir3
  |  |  |-sub_sub_main.py
  |  |  |-other_relevant.py
  |  |-sub_main1.py
  |-dir2
  |  |-sub_main2.py
  |-main.py

Sometimes I need to import functions from other_relevant.py in main.py , sub_main1.py , sub_main2.py , and sub_sub_main.py .有时我需要从other_relevant.py中的main.pysub_main1.pysub_main2.pysub_sub_main.py导入函数。 However, importing the script from different levels of the directory tree causes for the necessary import structure to change.但是,从目录树的不同级别导入脚本会导致必要的导入结构发生变化。

The code in other_relevant.py and sub_sub_main.py relies on code in other python files in subsubdir1 , subsubdir2 , and subsubdir3 . other_relevant.pysub_sub_main.py中的代码依赖于subsubdir1subsubdir2subsubdir3中其他 python 文件中的代码。 When I change where I import those two files the import statements in all the python files in those subdirectories have to be changed.当我更改导入这两个文件的位置时,必须更改这些子目录中所有 python 文件中的导入语句。

If I run main.py or sub_main2.py which imports other_relevant.py , it requires the import in other_relevant.py to use from dir.subdir1.subsubdir1.file import... .如果我运行导入other_relevant.pymain.pysub_main2.py ,则需要导入other_relevant.py才能使用from dir.subdir1.subsubdir1.file import...

If I am running the sub_main.py script then the import statement becomes from subdir.subsubdir1.file import...如果我正在运行sub_main.py脚本,那么导入语句将变为from subdir.subsubdir1.file import...

If I run sub_sub_main.py then the import statement becomes from subsubdir1.file import... .如果我运行sub_sub_main.py则导入语句变为from subsubdir1.file import...

Since the file structure makes sense in terms of how to organize the files I don't want to really change that.由于文件结构在如何组织文件方面很有意义,所以我不想真正改变它。 Is there a way to manage the import statements so that I don't have to change all the import statements in the files in subdir depending on where I run sub_sub_main.py and other_relevant.py ?有没有办法管理导入语句,这样我就不必根据运行sub_sub_main.pyother_relevant.py的位置更改subdir中文件中的所有导入语句?

Set the env variable PYTHONPATH to your top folder path.将环境变量PYTHONPATH设置为您的顶级文件夹路径。 Then all import statement will be made relative to this folder wherever you execute a python script.然后,无论您在哪里执行 python 脚本,所有导入语句都将相对于此文件夹进行。 For instance from sub_main2.py you can do:例如从sub_main2.py你可以这样做:

from dir.subdir.subdir3 import *

Setting up the env variable can be done by sourcing a sourceme.sh file located at the folder path.可以通过获取位于文件夹路径中的 sourceme.sh 文件来设置环境变量。 or directly in the.bashrc if only one project is used.如果只使用一个项目,则直接在.bashrc 中。

sample sourceme.sh:示例sourceme.sh:

export PYTHONPATH=`pwd -P`

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

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