The version of Python I'm using is 3.6.
If you find any mistakes, I would be grateful if you could point them out in the comments.
Suppose you want to load your own modules under `lib``` from`
scripts / execute.py``` with such a directory structure.
.
├──scripts
│ └── execute.py
└──lib
└── my_module.py
Initially, I tried to deal with it by writing execute.py
as follows and adding a file to `` `sys.path```.
import pandas as pd
import sys
sys.path.append('../lib')
import my_module
# (The following is omitted)
However, this is the Python coding convention PEP8 (Japanese translation io / ja / latest / #)) is violated, so if you are using flake8 etc., the following Tsukkomi will be entered.
E402 module level import not at top of file
Let's quote corresponding part of Japanese translation.
The import statement should always be placed at the beginning of the file, immediately after the module comment or docstring, and before the module's global variable or constant definition.
Just I had a question on Stackoverflow to the same effect.
Several methods were answered in this, and adding a directory to the environment variable `` `PYTHONPATH``` seemed to be the essential solution. (The following link was introduced)
(Although the following methods were also introduced, honestly, it looks like a cunning hack to me.)
pathmagic.py
that describes the path reading process and import itAlso, the Japanese question site teratail had answers to similar questions. The answer is from Sphinx committer Shimizukawa, so it seems to be highly credible.
Adjusting sys.path in a script is not recommended. If the directory where you want to use the library is fixed in various places and you want to import that library, there is a way to set the environment variable PYTHONPATH.
So I added the `` `libdirectory to PYTHONPATH and dealt with it. If you use it every time, write it in
bash_profile```.
export PYTHONPATH="${PYTHONPATH}:/full path of lib directory/lib"
This allowed us to remove the `` `sys.pathrelated description from
execute.py```.
import pandas as pd
import my_module
# (The following is omitted)
It's not the main subject, but I was curious about what would happen if the library name and my own module name were batting.
In such cases, read the official documentation. There is the following description in the official Python tutorial.
When importing a module named spam, the interpreter first looks for a built-in module with that name. If not found, look for a file named spam.py in the list of directories in sys.path. sys.path is initialized to the following location:
- The directory containing the entered script (or the current directory if no file is specified).
Apparently, the one in PYTHONPATH has priority. Even when I actually tried it, it behaved like that.
Recommended Posts