Python 3.x - How to get the directory where user installed package
<p>Suppose that I am building a Python package with the following folder tree:</p>

<pre><code>main
|-- setup.py
|-- the_package
     |--globar_vars.py
     |--the_main_script.py
</code></pre>

<p>When the user performs anyway to install it, like:</p>

<pre><code>sudo python setup.py install
python setup.py install --user
python setup.py install --prefix=/usr/local
</code></pre>

<p>Or well, using PIP:</p>

<pre><code>pip install 'SomeProject'
</code></pre>

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

<pre><code>globarl_vars.py
#!/usr/bin/env python3

user_installed_pkg = '/some/path/where/the/package/was/installed'
</code></pre>

<p>There is someway to get it? Thanks in advance.</p>

<p>Assuming your <code>SomeProject</code> package is a <a href="https://packaging.python.org/distributing/" rel="nofollow">well-formed Python package</a> (which can be done using <a href="https://setuptools.readthedocs.io/en/latest/setuptools.html" rel="nofollow">setuptools</a>), a user can derive the location simply use the <a href="https://setuptools.readthedocs.io/en/latest/pkg_resources.html" rel="nofollow"><code>pkg_resources</code></a> module provided by <code>setuptools</code> package to get this information.  For example:</p>

<pre><code>&gt;&gt;&gt; from pkg_resources import working_set
&gt;&gt;&gt; from pkg_resources import Requirement
&gt;&gt;&gt; working_set.find(Requirement.parse('requests'))
requests 2.2.1 (/usr/lib/python3/dist-packages)
&gt;&gt;&gt; working_set.find(Requirement.parse('requests')).location
'/usr/lib/python3/dist-packages'
</code></pre>

<p>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 <a href="https://setuptools.readthedocs.io/en/latest/pkg_resources.html#resourcemanager-api" rel="nofollow">Resource manager API</a> to access resources in those cases.</p>

<pre><code>&gt;&gt;&gt; import pkg_resources
&gt;&gt;&gt; api_src = pkg_resources.resource_string('requests', 'api.py')
&gt;&gt;&gt; api_src[:25]
b'# -*- coding: utf-8 -*-\n\n'
</code></pre>

python installation packages