确定当前python安装父路径,python文件夹名称和完整路径

时间:2012-10-29 18:40:47

标签: python path installation cross-platform instance

Windows上的

sys.prefix是python文件夹,但是linux通常指向/ usr,现在意味着必须按名称搜索目录,除非有另一种方法。

有吗?

依赖于文件夹名称也是混乱的,'Python27','python2.7'只是为了说出频繁的名称。

这个脚本是否过度杀伤?我这样做了吗?

os.environ无法帮助,因为可能没有PYTHON_PATH,或者运行中可能不匹配

sys.executable无法提供帮助,因为它只能在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))

1 个答案:

答案 0 :(得分:3)

获取路径是不够的

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