The "project directory Structure" is also a category of "readability and maintainability".
How directory is organized
There are already some common directory structures for how to organize a better Python project directory structure. On this issue of StackOverflow, we can see the discussion of the Python directory structure.
This is already very good, I do not intend to rebuild the wheel to enumerate the different ways, which I say my understanding and experience.
Assuming that your project is named Foo, I would recommend the most convenient and quick directory structure that would suffice:
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:
bin/
: Store some executable files of the project, of course you can name and script/
so on.
- conf/: Storing project configuration files
foo/
: stores all source code for the project. (1) All modules and packages in the source code should be placed in this directory. Do not place the top level directory. (2) Its subdirectory tests/
holds unit test code, and (3) The entrance of the program is preferably named main.py
.
docs/
: Store some documents.
setup.py
: Install, deploy, and package the scripts.
requirements.txt
: A list of external Python packages that store software dependencies.
README
: Project description file.
In addition, there are a number of scenarios that give more content. For example LICENSE.txt
, ChangeLog.txt
files and so on, I am not listed here, because these things are mainly open source projects need to use. 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
Take directory structure For example, we in main.py, use Bin directory file, first need to find foo/directory, then can import foo/sub-directory module, and need to do automatic acquisition, cannot write dead, this time use to OS module
Import OS
Import Sys
1. Find the absolute path to the file
Os.path.abspath (__file__) #获取文件的绝对路径, including file name
2. Get the Directory of files
Os.path.dirname (Os.path.abspath (__file__)) # For example main.py's directory 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 environment variable
Sys.path.append (Base_dir)
5, import the required directory
①. Import Bin
②. From bin Import *
Two ways to import, each has advantages and disadvantages, follow-up will be explained in detail, at this point, you can use the modules of other directories, welcome you crossing message Pointing
Python Software directory structure specification-how to import additional catalog modules with environment variables