gpt4 book ai didi

python - 以编程方式确定 pip 'user install' 位置 Scripts 目录

转载 作者:行者123 更新时间:2023-12-04 15:26:23 28 4
gpt4 key购买 nike

pip's documentation 中所述用户可以使用 pip install --user <pkg> 在他的个人帐户中安装软件包.

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

例如,在 Windows 中安装时 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.

是否有一些 python 代码可以用来以编程方式确定该位置(适用于 Windows/Linux/Darwin/等)?就像是:
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

作为后备,是否可以运行一些命令来获取此位置?类似于(但对于脚本位置而不是站 pip 的基本目录):
PS C:\Users\myusername\> python -m site --user-base
C:\Users\myusername\AppData\Roaming\Python

$ python -m site --user-base
/home/myusername/.local

最佳答案

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

import os
import sysconfig

user_scripts_path = sysconfig.get_path('scripts', f'{os.name}_user')
print(user_scripts_path)
但也可能是 pip 在内部使用了不同的逻辑(可能基于 distutils ),但结果应该仍然相同。
更新 : 自 pip 21.3发布于 2021-10-11, pip moved to using sysconfig to compute paths .
引用文献
  • https://docs.python.org/3/library/sysconfig.html#installation-paths
  • https://docs.python.org/3/library/os.html#os.name
  • https://discuss.python.org/t/proper-way-to-determine-install-location-of-console-scripts/7188
  • https://pip.pypa.io/en/stable/news/#deprecations-and-removals
  • 关于python - 以编程方式确定 pip 'user install' 位置 Scripts 目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62162970/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com