2

Suppose that I am building a Python package with the following folder tree:

main
|-- setup.py
|-- the_package
     |--globar_vars.py
     |--the_main_script.py

When the user performs anyway to install it, like:

sudo python setup.py install
python setup.py install --user
python setup.py install --prefix=/usr/local

Or well, using PIP:

pip install 'SomeProject'

I want that the folder where the package was installed be saved on the global_vars.py, in any variable, Eg:

globarl_vars.py
#!/usr/bin/env python3

user_installed_pkg = '/some/path/where/the/package/was/installed'

There is someway to get it? Thanks in advance.

2 Answers 2

1

Assuming your SomeProject package is a well-formed Python package (which can be done using setuptools), a user can derive the location simply use the pkg_resources module provided by setuptools package to get this information. For example:

>>> from pkg_resources import working_set
>>> from pkg_resources import Requirement
>>> working_set.find(Requirement.parse('requests'))
requests 2.2.1 (/usr/lib/python3/dist-packages)
>>> working_set.find(Requirement.parse('requests')).location
'/usr/lib/python3/dist-packages'

However, the path returned could be something inside an egg which means it will not be a path directly usable through standard filesystem tools. You generally want to use the Resource manager API to access resources in those cases.

>>> import pkg_resources
>>> api_src = pkg_resources.resource_string('requests', 'api.py')
>>> api_src[:25]
b'# -*- coding: utf-8 -*-\n\n'
Sign up to request clarification or add additional context in comments.

Comments

0
import wtv_module
print(wtv_module.__file__)

import os
print(os.path.dirname(wtv_module.__file__))

2 Comments

I was considering this option. However, this way only work when the package is already installed. I mean, your answer just solve the half of the problem. I get the path where the package was installed (great), now it remain to assign that path to the variable into the global_var.py file (which is also already installed).
Ok, may be splitting the work could be the solution ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.