I have a question about adding project path to python, for facilitating import
effort.
When I write code in Python, I usually add necessary path to sys.path
by using
import sys
sys.path.append("/path/to/dir/") # almost every `.py` need this
Sometimes, when my project gets bigger with many levels of directories, this approach seems bulky and error-prone (especially when I re-organize my files)
Recently, I start using a bash script (located at project root directory) that adding the sys.path.append
with project root argument to .py
file in the project. With this approach, I hardly have to manually care about importing a module.
My question is: Is that a good practice? I find it convenient for myself, compared to my old method, but since the bash script is a separated file, I need 2 command to run any script in my project (one for the bash and one for the .py
). I can include the command calling .py
to the bash, but it far less flexible than directly call it from terminal.
Really want to hear some advices! Thanks in advance. Any suggestion will be gratefully appreciated!
This is because the project's root directory is not added to the Python path. To fix this, add the following line to the import_class () function in the core/utils.py before calling __import__ ()
sys.path is a built-in variable within the sys module. It contains a list of directories that the interpreter will search in for the required module. Attention geek!
APPENDING PATH- append () is a built-in function of sys module that can be used with path variable to add a specific path for interpreter to search. The following example shows how this can be done. Python3
You can create a project by reusing a specified directory as its root directory. The project name is the same as the name of the specified root directory. This command is useful for dividing a large directory hierarchy within a single project into one or more subprojects.
It is generally not good practice to use manipulate sys.path
within a python library or program. You should add the relevant paths to the PYTHONPATH
in the calling environment for your python program:
PYTHONPATH="/path/to/other/projects/directory:$PYTHONPATH" python ...
or
export PYTHONPATH="/path/to/other/projects/directory:$PYTHONPATH"
python ...
This allows you to easily manipulate the paths that your program or library will search for dependencies easily without modifying your code.
It is also very easy to manage this in your personal development environment by modifying your bashrc
or in your production environments in your init
script (or other wrapper script) and provides you with one place to update each time you add or modify your project paths.
Given that you mention that you have almost one directory per .py
file, you should also consider how your code might be organized into packages to further simplify your setup.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With