以编程方式确定 pip '用户安装'位置 脚本目录

Ale*_*ros 10 python pip

正如pip 文档中所解释的,用户可以使用pip install --user <pkg>.

如何以编程方式确定像这样安装的脚本的用户安装位置?我说的是应该添加到 PATH 中的目录,以便可以从命令行调用已安装的包。

例如,在 Windows 中安装时,我收到以下警告,因为我的 PATH 中pip install -U pylint --user没有:'C:\Users\myusername\AppData\Roaming\Python\Python37\Scripts'

...
Installing collected packages: wrapt, six, typed-ast, lazy-object-proxy, astroid, mccabe, isort, colorama, toml, pylint
  Running setup.py install for wrapt ... done
  WARNING: The script isort.exe is installed in 'C:\Users\myusername\AppData\Roaming\Python\Python37\Scripts' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The scripts epylint.exe, pylint.exe, pyreverse.exe and symilar.exe are installed in 'C:\Users\myusername\AppData\Roaming\Python\Python37\Scripts' which is not on PATH.
Run Code Online (Sandbox Code Playgroud)

是否有一些 python 代码可以用来以编程方式确定该位置(适用于 Windows/Linux/Darwin/etc)?就像是:

def get_user_install_scripts_dir():
    ...
    # would return 'C:\Users\myusername\AppData\Roaming\Python\Python37\Scripts'
    # on Windows with Python 3.7.x, '/home/myusername/.local/bin' in Linux, etc
    return platform_scripts_dir
Run Code Online (Sandbox Code Playgroud)

作为后备方案,我可以运行一些命令来获取此位置吗?类似于(但对于脚本位置而不是站点的基本目录):

PS C:\Users\myusername\> python -m site --user-base
C:\Users\myusername\AppData\Roaming\Python

$ python -m site --user-base
/home/myusername/.local
Run Code Online (Sandbox Code Playgroud)

sin*_*roc 12

我相信以下应该给出预期的结果

import os
import sysconfig

user_scripts_path = sysconfig.get_path('scripts', f'{os.name}_user')
print(user_scripts_path)
Run Code Online (Sandbox Code Playgroud)

命令行:

python -c 'import os,sysconfig;print(sysconfig.get_path("scripts",f"{os.name}_user"))'
Run Code Online (Sandbox Code Playgroud)

自2021 年 10 月 11 日发布pip 21.3以来, pip本身用于sysconfig计算 paths

参考