user1576916
user1576916

Reputation: 1

determine current python installation parent path, python folder name, and full path

on windows sys.prefix is the python folder, but linux it points to /usr generally which now means a directory hunt by name must occur unless there is another way.

Is there?

Relying on the folder name is chaotic too, 'Python27', 'python2.7' just to name the frequent ones.

Is this script overkill? Am I doing this right?

os.environ can't help because there may not be a PYTHON_PATH, or whats running may not match

sys.executable can't help because it would only be right on windows.

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# rev 0.0.0.1
import os, platform, sys
"""File: _python_pfn.py
Seems excessive...
3 imports, 3 functions, 30 lines just to 
determine current python installation parent path, python folder name, and full path
"""
def _python_parent():
    """assume linux, but if windows just return sys.prefix"""
    ret = os.path.join('{}'.format(sys.prefix), 'lib')
    if platform.uname()[0] == 'Windows':
        ret = '{}'.format(sys.prefix)
    return ret

def _python_name(path):#, major=None, minor=None
    """assume windows, but if not listdir and find"""
    ma, mi = (str(sys.version_info[0]), str(sys.version_info[1]))
    #if major is not None: ma = str(major)
    #if minor is not None: ma = str(minor)
    ret = os.path.split(path)[1]
    if platform.uname()[0] != 'Windows':
        ls = [k for k in os.listdir(path) if os.path.isdir(os.path.join(path, k)) ]
        for k in ls:
            if k.lower().find('python') != -1:
                if k.find(ma) != -1:
                    if k.find(mi) != -1:
                        ret = k
    return ret

def _python_path(path):
    """use as _python_path(_python_parent())"""
    return os.path.join(path, _python_name(path))

Upvotes: 0

Views: 239

Answers (1)

Anurag Uniyal
Anurag Uniyal

Reputation: 88737

Isn't it enough to get the path

>>> import os
>>> os.path.dirname(os.__file__)
'/usr/lib/python2.7'

Upvotes: 3

Related Questions