How to refresh sys.path?
Asked Answered
C

2

19

I've installed some packages during the execution of my script as a user. Those packages were the first user packages, so python didn't add ~/.local/lib/python2.7/site-packages to the sys.path before script run. I want to import those installed packages. But I cannot because they are not in sys.path.

How can I refresh sys.path?

I'm using python 2.7.

Carrycarryall answered 19/8, 2014 at 13:39 Comment(0)
C
24

As explained in What sets up sys.path with Python, and when? sys.path is populated with the help of builtin site.py module.

So you just need to reload it. You cannot it in one step because you don't have site in your namespace. To sum up:

import site
from importlib import reload
reload(site)

That's it.

Carrycarryall answered 19/8, 2014 at 13:39 Comment(1)
This will solve most of the problems. If you deleted or renamed a file, pay attention to remove the old bytecode, otherwise, it will be used by Python. And if you are using Python 3 (I know the question is about 2.7 but I ended up here searching for a solution for 3), then remember to use importlib.invalidate_caches() or the old content of the file system may be used.Brazilin
P
2

It might be better to add it directly to your sys.path with:

import sys
sys.path.append("/your/new/path")

Or, if it needs to be found first:

import sys
sys.path.insert(1, "/your/new/path")
Poucher answered 5/4, 2018 at 14:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.