When doing large projects in python, there are often import problems. For example, when you import another py file that doesn't exist in your run path, you get an error.
There are probably two ways to do this:
If you are in a terminal, you can add the runtime path; if you are in a pycharm environment, you can right-click Mark Directory as Sources Root.
A chestnut: vim
def add(a, b): return a + b
vim
import head a = 3 b = 4 c = (a, b) print(c)
Let's put and under a path with the following file structure:
my_path
├──
└──
Let's run:
cd my_path python
There's nothing wrong with running it successfully straight away. But what if the path relationships were more complex? For example
my_path
├── folder_a
│ └──
└── folder_b
└──
If cd my_path/folder_a and then python . It will definitely report a path error. At this time, if you are developing this project with pycharm, you can just
The penultimate line, mark directory as source root, sets folder_b as a source root directory, so that files under folder_b can be imported directly without prefixes.
If you're running in terminal, there's no way to design it like pycharm, or if you need to deploy from pycharm to terminal, you can use () to add the source path.
Let's just add two sentences:
import sys ('../folder_b') import head a = 3 b = 4 c = (a, b) print(c)
You only need to add two lines at the beginning to complete the designation of the source path, and all py under the source path can be imported directly without prefixing. have you learned to waste
Supplementary: Python domestic mirror source path and setup method
Recently learn Python need to install third-party libraries, basically foreign sites, the installation is slow, so I found a solution, recorded: use Python domestic mirror source path, you can quickly install.
Summary of domestic source paths:
Tsinghua:/simple
Aliyun: /pypi/simple/
University of Science and Technology of China /simple/
Huazhong University of Science and Technology:/
Shandong University of Technology:/
Douban: /simple/
Use Cases:
Example: pip3 install -i /simple/ package name
Temporary use mode:
You can use pip with the argument -i /simple
For example: pip install -i /simple pyqt5, this will go and install the pyqt5 library from the Tsinghua side of the image.
Permanent modification of usage:
Under Linux, modify ~/.pip/ (create a folder and file if you don't have one. Folders should have a "." to indicate that it is a hidden folder)
The content is as follows:
[global] index-url = /simple [install] trusted-host=
Under windows, directly create a pip directory in the users directory, and then create a new file. (For example: C:\Users\WQP\pip\) The content is the same as above.
The above is a personal experience, I hope it can give you a reference, and I hope you can support me more. If there is any mistake or something that has not been fully considered, please do not hesitate to give me advice.