How do I find the location of my Python site-packages directory?

前端 未结 21 2666
梦谈多话
梦谈多话 2020-11-22 03:06

How do I find the location of my site-packages directory?

21条回答
  •  甜味超标
    2020-11-22 03:22

    I had to do something slightly different for a project I was working on: find the relative site-packages directory relative to the base install prefix. If the site-packages folder was in /usr/lib/python2.7/site-packages, I wanted the /lib/python2.7/site-packages part. I have, in fact, encountered systems where site-packages was in /usr/lib64, and the accepted answer did NOT work on those systems.

    Similar to cheater's answer, my solution peeks deep into the guts of Distutils, to find the path that actually gets passed around inside setup.py. It was such a pain to figure out that I don't want anyone to ever have to figure this out again.

    import sys
    import os
    from distutils.command.install import INSTALL_SCHEMES
    
    if os.name == 'nt':
        scheme_key = 'nt'
    else:
        scheme_key = 'unix_prefix'
    
    print(INSTALL_SCHEMES[scheme_key]['purelib'].replace('$py_version_short', (str.split(sys.version))[0][0:3]).replace('$base', ''))
    

    That should print something like /Lib/site-packages or /lib/python3.6/site-packages.

提交回复
热议问题