Software Directory Structure Specification

directory organization

There are already some agreed-upon directory structures on how to organize a good Python project directory structure. In this question on Stackoverflow , you can see everyone talking about the Python directory structure.

Assuming your project is named foo, the most convenient and quick directory structure I suggest is enough:

Foo/
|-- bin/
|   |-- foo
|
|--conf/
|  |--__init__.py
|  |--settings.py
| |-- foo/ | |-- tests/ | | |-- __init__.py | | |-- test_main.py | | | |-- __init__.py | |-- main.py | |-- docs/ | |-- conf.py | |-- abc.rst | |-- setup.py |-- requirements.txt |-- README

Briefly explain:

  1. bin/: Store some executable files of the project, of course, you can name script/it and so on.
  2. conf/: store the project configuration file
  3. foo/: holds all the source code of the project. (1) All modules and packages in the source code should be placed in this directory. Don't put it in the top-level directory. (2) Its subdirectory tests/stores unit test code; (3) The entry of the program is best named main.py.
  4. docs/: Store some documents.
  5. setup.py: Scripts for installation, deployment, packaging.
  6. requirements.txt: A list of external Python packages that store software dependencies.
  7. README: Project description file.

In addition, there are some programs that give more content. For example LICENSE.txt, ChangeLog.txtfiles, etc., I did not list here, because these things are mainly used when the project is open source. If you want to write an open source software, how to organize the directory, you can refer to this article .

How to use files in different directories

The directory structure in the above figure is an example. In main.py, we use the files in the bin directory. First, we need to find the Foo/ directory, and then import the modules in the subdirectories under Foo/, and we need to obtain it automatically, and cannot write to death. At this time, the os module is used

import them

import sys

1. Find the absolute path of the file

os.path.abspath(__file__) #Get the absolute path of the file, including the file name

2. Get the directory of the file

os.path.dirname(os.path.abspath(__file__) ) # For example, the directory of main.py is foo/ 

3. Get the parent directory of the file directory again

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__) ))

4. Add to the environment variable

sys.path.append(BASE_DIR)

5. Import the required directory

①.  import bin

②. from bin import *

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324942923&siteId=291194637