use python When doing large projects , Often import problem . such as , When you import the other one py When you file , This py It doesn't exist in your running path , It's a mistake .
There are probably two ways : If in terminal in , We can go through sys.path.append To add a run path ; If in pycharm In the environment , We can right-click Mark Directory as Sources Root.
Take a chestnut :vim head.py
def add(a, b):
return a + b
vim run.py
import head
a = 3
b = 4
c = head.add(a, b)
print(c)
Let's put head.py and run.py Put it under a path , The file structure is as follows :
my_path
├── head.py
└── run.py
Let's run run.py:
cd my_path
python run.py
There is no problem with direct successful operation . however , If the path relationship is more complicated ? such as
my_path
├── folder_a
│ └── run.py
└── folder_b
└── head.py
If cd my_path/folder_a, then python run.py. There will be a path error . This is the time , If you use pycharm Developing this project , You can directly
The third to last line ,mark directory as source root. Put... Directly folder_b Set to a source root , such folder_b All the documents below can be directly Without a prefix By import.
If you are stay terminal function , There's no way to be like pycharm So design , Or from pycharm Deploy to terminal when , You can use it. sys.path.append() To add a source path . We just need to add two sentences :
import sys
sys.path.append('../folder_b')
import head
a = 3
b = 4
c = head.add(a, b)
print(c)
You only need to add the first two lines of the source , All in the source path py Can be prefixed directly import. Did you stop learning