【Python】Linux服务器运行.sh文件的环境问题

文章讲述了在conda环境中运行.sh脚本时遇到torch模块未找到的错误。解决方案是在.sh文件中首先进行conda环境的初始化,通过添加和激活指定环境的命令。这需要在.sh文件开头复制.bashrc中的conda初始化代码,并激活所需环境。
摘要由CSDN通过智能技术生成

问题:

已经在conda中安装好环境并进入了,在该环境中运行.sh文件,却报错:

ModuleNotFoundError: No module named 'torch'

 解决方案:

在shell文件中启动anaconda的虚拟环境。

如果直接在.sh文件写:

conda activate env_name

会报错:

CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
To initialize your shell, run

    $ conda init <SHELL_NAME>

Currently supported shells are:
  - bash
  - fish
  - tcsh
  - xonsh
  - zsh
  - powershell

See 'conda init --help' for more information and options.

IMPORTANT: You may need to close and restart your shell after running 'conda init'.

要实现在.sh文件中进入配置好的conda环境,需要在bash先初始化conda,方法如下:

在目录下找到隐藏文件.bashrc,打开.barshrc,在文件的最后找到下面这段:

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

将上面这段代码复制到.sh文件的开头,再在其后加上:

conda activate env_name

 然后再运行.sh文件,这个时候就能正常的在配置好的环境里运行了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值