This is a convenient way to add our package folder to sys.path, which the Python interpreter will use to search for the package and modules if not present in the built-in library. Depending on the operating system we are using, we can define this variable as follows.
In Windows, the environment variable can be defined using either of the following options:
• The command line: Set PYTHONPATH = "C:\pythonpath1;C:\pythonpath2". This is good for one active session.
• The graphical user interface: Go to My Computer | Properties | Advanced System Settings | Environment Variables. This is a permanent setting.
In Linux and macOS, it can be set using export PYTHONPATH= `/some/path/`.
If set using Bash or an equivalent terminal, the environment variable will be effective for the terminal session only. To set it permanently, it is recommended to add the environment variable at the end of a profile file, such as ~/bash_profile.
If we execute the pkgmain3.py program without setting PYTHONPATH, it returns an error: ModuleNotFoundError: No module named 'masifutil'. This is again expected as the path of the masifutil package is not added to PYTHONPATH.
In the next step, we will add the folder path containing masifutil to the PYTHONPATH variable and rerun the pkgmain3 program. This time, it works without any error and with the expected console output.
Using the .pth file under the Python site package
This is another convenient way of adding packages to sys.path. This is achieved by defining a .pth file under the Python site packages. The file can hold all the folders we want to add to sys.path.
For illustration purposes, we created a my.pth file under venv/lib/Python3.7/ site-packages. As we can see in Figure shown below, we added a folder that contains our masifutil package. With this simple .pth file, our main script pkymain3.py program works fine without any error and with expected console output:
The approaches we discussed to access custom packages are effective to reuse the packages and modules on the same system with any program. In the next blog, we will explore how to share packages with other developers and communities.
0 comments:
Post a Comment