您当前的位置:首页 > 计算机 > 软件应用 > 开发工具(IDE)

pycharm通过python包装器保留环境变量

时间:12-09来源:作者:点击数:

问题描述:pycharm内运行没有环境变量,但bash直接运行脚本却没有问题

Exception: 
Missing path to your environment variable. 
Current values LD_LIBRARY_PATH=
Please add following line to .bashrc:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/amax/.mujoco/mjpro150/bin

似乎只有 /etc/environment 里配置的 PATH 有生效,在 ~/.profile 或 ~/.bashrc 内配置似乎也没用

流程

包装器代码

下面是命令行

# 打开对应的envs的bin文件夹(python解释器的所在文件夹)
cd ~/anaconda3/envs/HVF_cuda101/bin/
# 填入下面的代码到 `pthon_profile` 文件中
vim python_profile
# 调整权限
chmod 777 python_profile

下面是python封装器 pthon_profile 的代码,务必小心这里的代码必须是“LF”格式结尾进行文件编写,要不运行会失败

#!/bin/bash

# Make sure that the bashrc was sourced, so that executing python
# via ssh does the same as executing python locally.
if ! (( $PROFILE_SOURCED )); then
   echo "PYTHON_BASHRC will run ~/.profile and add the environment variables"
   . ~/.profile
fi

# Get the directory of this script, see 
__dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Execute the original python.
${__dir}/python "$@"

profile和bashrc的协动

核心profile的代码

# ~/.profile: executed by the command interpreter for login shells.
# This file is not read by bash(1), if ~/.bash_profile or ~/.bash_login
# exists.
# see /usr/share/doc/bash/examples/startup-files for examples.
# the files are located in the bash-doc package.

# the default umask is set in /etc/profile; for setting the umask
# for ssh logins, install and configure the libpam-umask package.
#umask 022

# if running bash
if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
        . "$HOME/.bashrc"
    fi
fi

# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
    PATH="$HOME/bin:$PATH"
fi

# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/.local/bin" ] ; then
    PATH="$HOME/.local/bin:$PATH"
fi

# add by defoe
# if you want to add PATH, can use the "BASHRC_SOURCED" of ".bashrc" to customization
if ! (( $BASHRC_SOURCED )); then
    export PATH="$HOME/bin:$HOME/.local/bin:$PATH"
    export PATH="/home/amax/anaconda3/bin:$PATH"
fi

export LD_LIBRARY_PATH=~/.mujoco/mjpro150/bin${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}
export MUJOCO_KEY_PATH=~/.mujoco${MUJOCO_KEY_PATH}
export MUJOCO_PY_MJKEY_PATH=~/.mujoco/mjkey.txt
export MUJOCO_PY_MUJOCO_PATH=~/.mujoco/mjpro150

# add by defoe, should be end of the file
# if you want to add PATH, can use the "BASHRC_SOURCED" of ".bashrc" to customization
export PROFILE_SOURCED=1

协动的bashrc

这里主要是提供 BASHRC_SOURCED 作为运行的标志,看 profile 是否需要额外配置PATH变量

# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth

# append to the history file, don't overwrite it
shopt -s histappend

# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000

# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

# If set, the pattern "**" used in a pathname expansion context will
# match all files and zero or more directories and subdirectories.
#shopt -s globstar

# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
    xterm-color|*-256color) color_prompt=yes;;
esac

# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
#force_color_prompt=yes

if [ -n "$force_color_prompt" ]; then
    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
        # We have color support; assume it's compliant with Ecma-48
        # (ISO/IEC-6429). (Lack of such support is extremely rare, and such
        # a case would tend to support setf rather than setaf.)
        color_prompt=yes
    else
        color_prompt=
    fi
fi

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
    ;;
*)
    ;;
esac

# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
    test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
    alias ls='ls --color=auto'
    #alias dir='dir --color=auto'
    #alias vdir='vdir --color=auto'

    alias grep='grep --color=auto'
    alias fgrep='fgrep --color=auto'
    alias egrep='egrep --color=auto'
fi

# colored GCC warnings and errors
#export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'

# some more ls aliases
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'

# Add an "alert" alias for long running commands.  Use like so:
#   sleep 10; alert
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'

# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if ! shopt -oq posix; then
  if [ -f /usr/share/bash-completion/bash_completion ]; then
    . /usr/share/bash-completion/bash_completion
  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi

# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/home/amax/anaconda3/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
    eval "$__conda_setup"
else
    if [ -f "/home/amax/anaconda3/etc/profile.d/conda.sh" ]; then
        . "/home/amax/anaconda3/etc/profile.d/conda.sh"
    else
        export PATH="/home/amax/anaconda3/bin:$PATH"
    fi
fi
unset __conda_setup
# <<< conda initialize <<<

# add by defoe, should be end of the file
export BASHRC_SOURCED=1

pycharm的设置教程

python对环境变量的测试

import os  
print("\nnow is python")  
print(os.environ.get("PATH"))  
print(os.environ.get("DISPLAY"))  
print(os.environ.get("LD_LIBRARY_PATH"))

缺点是pycharm无法通过封装器获取pip包的信息,但还是可以通过下面的方法更新新安装的pip信息

如果代码中有红点,提示没有相应的安装包

选择的原因

.profile instead of .bashrc

.bashrc包含使在交互式shell中工作更容易的命令(设置别名,激活虚拟环境)。在.profile中,一般放交互式和非交互式shell都需要的命令,例如,设置重要库的路径。

我为远程Python解释器提供了.profile而不是.bashrc,以避免不必要的环境混乱,并确保与在非交互式(登录)shell中调用python的设置相同。

此外,指定作为远程解释器的shell包装器must be silent.如果你将.bashrc作为源码,并且它包含一个打印出类似"Activated my_conda_env"的信息的命令,这将会扰乱PyCharm的远程调试器。

bashrc不能用于报装器的原因

这里可以看到,如果是非交互的bash,bashrc 是不会真正运行的。

相应的profile文件没有这个设定,所以应该是 包装器和profile协动。

包装器调用python,通过profile设定环境变量。

Replacing python3.x with the shell wrapper

PyCharm的远程解释器和远程调试器并不要求shell包装器有一个特定的名字。

然而,我观察到其他功能,如PyCharm的打包工具(pip等),希望解释器有一个标准名称(pythonpython3python3.6)。因此,我需要将python命令封装为shell包装器本身 python_profile

暂时不将python改名,python保持原样,只是pycharm的python解释器改用 python_profile

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门