Reputation: 615
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.
Upvotes: 2
Views: 1298
Reputation: 18908
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'
Upvotes: 1
Reputation: 3791
import wtv_module
print(wtv_module.__file__)
import os
print(os.path.dirname(wtv_module.__file__))
Upvotes: 0