Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a Python import path using a .pth file

If I put a *.pth file in site-packages it's giving an ImportError. I'm not getting how to import by creating a *.pth file.

(Refers to importing in python)

like image 859
user46646 Avatar asked Mar 31 '09 07:03

user46646


People also ask

How do you set a path to import in Python?

append() Function. This is the easiest way to import a Python module by adding the module path to the path variable. The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files.

What is __ file __ in Python?

__file__ is a variable that contains the path to the module that is currently being imported. Python creates a __file__ variable for itself when it is about to import a module.

How do I add Python path to environment variables in Ubuntu?

Setting path at Unix/LinuxIn the csh shell − type setenv PATH "$PATH:/usr/local/bin/python" and press Enter. In the bash shell (Linux) − type export PATH="$PATH:/usr/local/bin/python" and press Enter. In the sh or ksh shell − type PATH="$PATH:/usr/local/bin/python" and press Enter.

How do I change the path of a Python site package?

The easiest way to change it is to add a file /usr/local/lib/python2. 6/dist-packages/site-packages. pth containing ../site-packages . Alternatively, maybe you can teach the package to use site.


1 Answers

If you put a .pth file in the site-packages directory containing a path, python searches this path for imports. So I have a sth.pth file there that simply contains:

K:\Source\Python\lib

In that directory there are some normal Python modules:

logger.py
fstools.py
...

This allows to directly import these modules from other scripts:

import logger

log = logger.Log()
...
like image 53
sth Avatar answered Sep 30 '22 18:09

sth