【问题标题】:Correctly formatting a PYTHONPATH in my .bash_profile在我的 .bash_profile 中正确格式化 PYTHONPATH
【发布时间】:2019-11-13 13:22:52
【问题描述】:

我想将PYTHONPATH 添加到我的 .bash_profile 中,但想检查我是否以正确的方式执行此操作。我的.bash_profile(没有PYTHONPATH)看起来像:

# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi

# User specific environment and startup programs

PATH=$PATH:$HOME/.local/bin:$HOME/bin:/home/user/condor/bin:/home/user/merlin/bin

export PATH

我想添加到我的 PYTHONPATH 的路径是:

/home/user/merlin/bin/strats/

因此,我更新的 .bash_profile(使用 PYTHONPATH)看起来像:

    # .bash_profile

    # Get the aliases and functions
    if [ -f ~/.bashrc ]; then
            . ~/.bashrc
    fi

    # User specific environment and startup programs

    PATH=$PATH:$HOME/.local/bin:$HOME/bin:/home/user/condor/bin:/home/user/merlin/bin

    export PATH

    export PYTHONPATH=/home/user/merlin/bin/strats/

如何正确格式化?

【问题讨论】:

  • 嗯.. .bash_profile 是配置您希望在交互式 shell 中拥有的任何环境变量的地方。如果这是您想要的,并且您的 python 程序正在从该目录正确导入模块,我会说一切都好。这里唯一的问题是,如果系统范围的设置(即:/etc/environment、/etc/profile、/etc/profile.d/ 或 /etc/bash.bashrc)已经继承了 PYTHONPATH 变量。如果是这种情况,您将覆盖已设置的任何内容。
  • 你有机会测试吗?如果答案帮助您解决了问题,请接受或发表评论,以便进一步改进。

标签: bash pythonpath


【解决方案1】:

如果您希望成为交互式登录 shell 上 PYTHONPTAH 环境变量内容的唯一所有者和决策者,那么您做对了:

~/.bash_profile~/.profile

export PYTHONPATH=/home/user/merlin/bin/strats/

如果您想继承 PYTHONPATH 环境变量的任何系统范围设置,那么您应该:

~/.bash_profile~/.profile

export PYTHONPATH=$PYTHONPATH:/home/user/merlin/bin/strats/

请注意,如果您在一个无需登录即可启动新终端的系统中工作(即:在您的 linux 桌面上启动一个新的 xterm),或者您需要特定的环境变量来运行通过 cron 编写的脚本,.bash_profile 不会被执行,因此该脚本无法使用环境变量。

正如本答案 cmets 中所讨论的,您可以选择使用 ./~profile 文件而不是 ~/.bash_profile 来获得与其他 shell 的额外兼容性。

有些人只是在~/.bashrc 中添加所有环境配置。由于您的.bash_profile 模板调用~/.bashrc,您最终会在交互式登录和非登录shell 中使用这些环境变量。

对于通过 cron 运行的脚本,您应该直接在脚本本身或 cron 行上获取您的环境配置文件,因为这不会自动为您完成(crontab 启动非交互式 shell 来运行脚本和这些不受~/.bashrc~/.bash_profile~/.profile 的影响。

【讨论】:

  • 最好使用 ~/.profile 而没有 ~/.bash_profile (而不是在 ~/.bashrc 中设置),例如。在 ubuntu 18 上,所以环境变量只在登录时设置一次,而不是每次打开 shell 时都设置
  • @jenesaisquoi .bash_profile 在与.profile 相同的情况下来自(bash)。如果.bash_profile 存在,则由bash 使用代替 .profile
  • @chepner .profile 是在登录 ubuntu 18 时获得的,但 .bash_profile 不是
  • 对,关于 .bash_profile 而不是 .profile 的来源,这就是为什么我说最好只有 .profile,因为它更标准,可能适用于大多数窗口管理器
  • AFAIK,对于交互式登录 shell,bash 将首先获取 ~/.bash_profile(系统范围的 /etc/profile 除外)。只有当它没有找到~/.bash_profile 时,它才会获取~/.bash_login,如果它也没有找到它,它就会去寻找~/.profile。 bash 首先获取~/.profile 而不是~/.bash_profile 的唯一方法是使用sh 命令调用bash 作为模仿旧sh 行为的一种方式。
猜你喜欢
  • 1970-01-01
  • 2020-12-04
  • 2018-02-18
  • 2014-01-07
  • 1970-01-01
  • 1970-01-01
  • 2021-08-30
  • 1970-01-01
  • 2016-08-01
相关资源
最近更新 更多