以编程方式确定 pip 'user install' 位置 Scripts 目录 [英] Programmatically determine pip 'user install' location Scripts directory

查看:27
本文介绍了以编程方式确定 pip 'user install' 位置 Scripts 目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pip 的文档 中所述,用户可以安装软件包在他的个人帐户中使用 pip install --user .

As explained in pip's documentation a user can install packages in his personal account using pip install --user <pkg>.

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

How can I programmatically determine the user install location for scripts installed like this? I am talking about the directory that should be added to the PATH so that installed packages can be invoked from command line.

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

For example, in Windows when installing pip install -U pylint --user I get the following warning because I don't have 'C:\Users\myusername\AppData\Roaming\Python\Python37\Scripts' in my PATH:

...
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/等)?类似的东西:

Is there some python code I can use to determine that location programmatically (that will work on Windows/Linux/Darwin/etc)? Something like:

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

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

As a fallback, is there some command I can run to obtain this location? Something like (but for the script location not the site's base directory):

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

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

推荐答案

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

I believe the following should give the expected result

import os
import sysconfig

user_scripts_path = sysconfig.get_path('scripts', f'{os.name}_user')
print(user_scripts_path)

但可能是 pip 在内部使用了不同的逻辑(可能基于 distutils),但结果应该还是一样的.

But it might be that pip uses a different logic internally (probably based on distutils), but the results should still be the same.

参考资料

这篇关于以编程方式确定 pip 'user install' 位置 Scripts 目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆