Python add local path

How to Use Sys.path.append() in Python

Sys.path is a list of directories where the Python interpreter searches for modules. Mind you, this is a list! When a module is claimed in a project file, it will search through each one of the directories in the list. If the module is located within one of those directories, then everything goes fine and your project is successfully rendered. However, if the module is not located within any of the listed directories, then your project will fail lest you can “append” the directory where your module is located to the list using the append() function. In this tutorial, we’ll be learning about how to use sys.path.append() in Python.

List Current Path

By declaring the following, we can check the current Python path:

from pprint import pprint

Here, the pprint module is just used to make things look pretty, so you can ignore that part, and concentrate on the rest. All we’re trying to do here is to print out sys.path.

What you notice here is that first of all, it’s a list. So according to the list, it will first look in the current working directory, then in other directories one by one. The current working directory is the directory in which the main python script – the one being executed – is found. Further, what this also means is that this list can be modified or edited.

Читайте также:  Parser program in python

Adding a Path

The sys.path.append() method is used specifically to add a Path to the existing ones.

Suppose now that I have two distinct files: main.py, and file1.py. Main.py is the main file, and we’re going to try to import file1.py (a module that we wrote).

Because file1.py or our module is within the working directory, you should be able to successfully print out the secret sentence. This is so because when the Python interpreter searches for the requested module, it will search in the working directory first and because our module called file1 is within the working directory, it will automatically print out our secret sentence.

Now, suppose that I create a directory within my working directory called “directory1” and place my module called file1 within it.

Now, within the module file1 is the secret phrase that we’re trying to print out. In this case, it will not print out the secret phrase. Why? Because the interpreter isn’t looking in “directory1” for any modules. In other words, the current working directory is a member of the list of sys.path but “directory1” is not a member of that list. So, the resulting error is a ModuleNotFound Error – it couldn’t find or locate the module called file1.

In order to avert this problem, you need to tell the Python interpreter where to look for the module file1. This is where the sys.path.append() method comes in.

The sys.path.append() method is used to append the path that we want to the existing list.

On a Windows system, you’d write:

Please note that you cannot add any given file to sys.path, instead you may add directories, and then import the files you want.

Example #1

So, let’s try the previous operation (where the file1 module is located within directory1) again but this time, we’ll append the path to the file1 module to sys.path using the sys.path.append() method.

sys . path . append ( ‘C:\\Users\\never\\PycharmProjects\\

When we append the path using the sys.path.append() method, we first append the location of the module to Path, and then import it. If done in such a manner, the Python interpreter should be able to locate the requested module, and therefore retrieve the secret variable.

The output of the previous operation is as follows:

Example #2

Let’s take another example, this time on a Linux machine. Let’s suppose that we have one file – main.py.

from pprint import pprint

Here, sys.path[0] is “/home/kalyani” because that is where main.py is located.

Now, let’s modify the script a little bit by using the sys.path.append() method. Let’s use the method to append a particular path (‘/home/kalyani/directory1’) to sys.path.

from pprint import pprint

sys . path . append ( ‘/home/kalyani/directory1’ )

So, the sys.path.append() method has appended the path to the end of the existing list! Here, please also note that the appending is done at the end of the list not at the beginning.

PYTHONPATH

There is one tiny little problem with what we just did and that is that we didn’t permanently put that location onto the sys.path list. The sys.path.append() method is used to temporarily add a path and as such, that path would be valid for a session for example. If you’d like to permanently alter the sys.path list, then we can use PYTHONPATH to add the path to the list. Since sys.path also looks into PYTHONPATH, the locations listed will then be included in the list of paths.

  1. On your Linux machine, open up a terminal, and navigate to the folder containing .bashrc.
  2. nano .bashrc
  3. Add the following at the end of the .bashrc file:

Here, you can add the path that you want.

  1. Close the terminal, and open up a new terminal
  2. Now, try executing your program. In my case, it will be the following:

from pprint import pprint

When writing complex programs in Python, we will eventually add third party modules or even better, create our own modules. In all cases, we cannot keep every single Python file we create in one directory, we may wish to use multiple directories to adequately classify our files. The problem however is that we may need to import our created modules left and right. In such cases, if we want to prevent a ModuleNotFound Error, then we can add the location of the directory – and mind you, it has to be a directory, not a file – to sys.path using the sys.path.append() method.

Источник

How to import local modules with Python

Importing files for local development in Python can be cumbersome. In this article, I summarize some possibilities for the Python developer.

https://xkcd.com

TL; DR: I recommend using python -m to run a Python file, in order to add the current working directory to sys.path and enable relative imports.

Definitions

Script: Python file meant to be run with the command line interface.

Module: Python file meant to be imported.

Package: directory containing modules/packages.

Example

Consider the following project structure:

project ├── e.py └── src ├── a │ └── b.py └── c └── d.py 

Say that in b.py , we want to use d.py :

Let’s try to run python from the project directory:

~/Documents/code/project$ python3 src/a/b.py Traceback (most recent call last): File "/home/qfortier/Documents/code/project/src/a/b.py", line 4, in import src.c.d ModuleNotFoundError: No module named 'src' 

What happened? When Python tries to import a module, it looks at the paths in sys.path (including, but not limited to, PYTHONPATH):

~/Documents/code/project$ python3 src/a/b.py ['/home/qfortier/Documents/code/project/src/a', '/usr/lib/python38.zip', '/usr/lib/python3.8', . ] 

We see that the directory containing b.py (the script we run) is added to sys.path . But d.py is not reachable from the directory a , hence the above error.

1st solution: add root to sys.path

We can add the path to the root of the project:

~/Documents/code/project$ python3 src/a/b.py ['/home/qfortier/Documents/code/project/src/a', . '.'] 

The added path ‘.’ refers to the current working directory (from which Python was run) ~/Documents/code/project. Python can indeed import c.d from this directory.

This solution works regardless of the directory used to run Python:

~/Documents/code/project$ cd ../.. ~/Documents$ python3 code/project/src/a/b.py ['/home/qfortier/Documents/code/project/src/a', . 'code/project'] 

It should also work on a different computer, with a different filesystem or OS, thanks to Pathlib.
However, modifying sys.path at the beginning of every file is tedious and hard to maintain. A better solution would be to use a context.py file modifying sys.path and imported by every other file, but this is still unsatisfying.
Another possibility is to add the root directory to PYTHONPATH (before running the script). This is done automatically by poetry , for example.

Relative import

Relative imports were introduced in PEP 328 as a way to improve maintainability and avoid very long import statements. They must use the from .module import something syntax:

~/Documents/code/project$ python3 src/a/b.py Traceback (most recent call last): File "src/a/b.py", line 4, in from ..c import d ImportError: attempted relative import with no known parent package 

This is not working! Indeed, relative imports rely on the __name__ or __package__ variable (which is __main__ and None for a script, respectively).
If we import b.py from another file, everything is fine:

~/Documents/code/project$ python3 e.py Name: src.a.b Package: src.a 

Note: to go up several directories in relative imports, use additional dots: from . c import d would go 2 directories up, for example.

2nd solution: run as a module

It is unfortunate that scripts can’t use relative imports. PEP 338 overcomes this limitation by adding the -m option. With this option, a script is run as if it was imported as a module.

~/Documents/code/project$ python3 -m src.a.b # note that we use . and not / here Name: __main__ Package: src.a 

python3 -m src.a.b acts as if a Python file containing import src.a.b was run in the current directory, with two notable differences:

  • the __package__ variable is filled, enabling relative imports (see PEP 366)
  • the directory from which Python was run (here: ~/Documents/code/project) is added to sys.path

Since I don’t see any drawback to this, I recommend always using python3 -m to run a script.

Run as a module on Visual Code

The default launch configuration in Visual Code runs Python files as scripts (without -m ). This GitHub issue explains how to add -m automatically:

  • add the “Command Variable” extension to Visual Code
  • set the following Python launch configuration in your settings.json:

3rd solution : modify PYTHONPATH

With Visual Code, you can automatically add the root directory to your project by adding a line to the launch configuration :

Alternatively, you can add a .env file in the root directory :

4rd solution (outdated): install in editable mode

pip install -e . installs a package in editable mode, which can then be imported anywhere on the computer. In practice, this is essentially a symbolic link to your package. Therefore, any modification of the package is reflected on the code importing it. It requires a setup.py at the root of your package.

Note: according to PEP 517, this is no longer recommended: Python packages should rely on a toml file (see Poetry) and not on setup.py anymore.

References

Updated: May 9, 2021

Источник

Оцените статью