简体   繁体   中英

Python 3.x - How to get the directory where user installed package

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.

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'
import wtv_module
print(wtv_module.__file__)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM