Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a packed python package without installing it

I have a python 3 package with the following structure:

.
├── package
│   └── bin
        └── main_module
│   └── lib
│       ├── __init__.py
│       ├── module1.py
│       ├── module2.py
│       └── module3.py
│   └── test
│       ├── test1.py
│       ├── test2.py
│       └── test3.py
│   └── setup.py

Usually, one runs $ python3 setup.py install and all is good. However, I want to use this package on a cluster server, where I don't have write permissions for /usr/lib/. The following solutions came to my mind.

  1. Somehow install the package locally in my user folder.

  2. Modify the package such that it runs without installation.

  3. Ask the IT guys to install the package for me.

I want to avoid 3., so my question is whether 1. is possible and if not, how I have to modify the code (particularly the imports) in order to be able to use the package without installation. I have been reading about relative imports in python all morning and I am now even more confused than before. I added __init__.py to package and bin and from what I read I assumed it has to be from package.lib import module1, but I always get ImportError: No module named lib.

like image 737
bgbrink Avatar asked Jan 28 '23 16:01

bgbrink


2 Answers

In order for Python to be able to find your modules you need to add the path of your package to sys.path list. As a general way you can use following snippet:

from sys import path as syspath
from os import path as ospath

syspath.append(ospath.join(ospath.expanduser("~"), 'package_path_from_home'))

os.path.expanduser("~") will give you the path of the home directory and you can join it with the path of your package using os.path.join and then append the final path to sys.path.

If package is in home directory you can just add the following at the leading of your python code that is supposed to use this package:

syspath.append(ospath.join(ospath.expanduser("~"), 'package'))

Also make sure that you have an __init__.py in all your modules.

like image 64
Mazdak Avatar answered Jan 31 '23 07:01

Mazdak


I had the same problem. I used the first approach

  • install the package locally in my user folder by running

    python setup.py install --user

This will install your module in ~/.local/lib/python3/

like image 27
arvindkgs Avatar answered Jan 31 '23 09:01

arvindkgs