使用shell脚本激活VirtualEnv似乎不起作用

Gau*_*tam 46 shell terminal virtualenv

我尝试通过类似下面的shell脚本激活VirtualEnv,但它似乎不起作用,

#!/bin/sh
source ~/.virtualenvs/pinax-env/bin/activate
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

$ sh virtualenv_activate.sh 
virtualenv_activate.sh: 2: source: not found
Run Code Online (Sandbox Code Playgroud)

但如果我在终端上输入相同的命令它似乎工作

$ source ~/.virtualenvs/pinax-env/bin/activate
(pinax-env)gautam@Aspirebuntu:$
Run Code Online (Sandbox Code Playgroud)

所以我将shell脚本更改为

#!/bin/bash
source ~/.virtualenvs/pinax-env/bin/activate
Run Code Online (Sandbox Code Playgroud)

如建议和使用

$ bash virtualenv_activate.sh 
gautam@Aspirebuntu:$
Run Code Online (Sandbox Code Playgroud)

运行脚本.

这不会引发错误,但也不会激活虚拟环境

那么有关如何解决这个问题的任何建议?

PS:我使用的是Ubuntu 11.04

Mar*_*eth 62

TLDR

必须source单独运行.sh脚本而不是脚本

source your-script.sh
Run Code Online (Sandbox Code Playgroud)

而不是your-script.sh

细节

sh与bash不同(虽然有些系统只是将sh链接到bash,所以运行sh实际上运行bash).您可以将sh视为bash的淡化版本.bash所具有的一件事就是"源"命令.这就是为什么你得到了这个错误...源在你的bash shell中正常运行.但是当您使用sh启动脚本时,您将在子进程中的shell中运行该脚本.由于该脚本在sh中运行,因此找不到"source".

解决方案是在bash中运行脚本.将第一行更改为...

#!/bin/bash
Run Code Online (Sandbox Code Playgroud)

然后运行...

./virtualenv_activate.sh
Run Code Online (Sandbox Code Playgroud)

...要么...

/bin/bash virtualenv_activate.sh
Run Code Online (Sandbox Code Playgroud)

编辑:

如果要激活virtualenv来更改从中调用脚本的shell,则需要使用"source"或"dot operator".这可确保脚本在当前shell中运行(因此会更改当前环境)...

source virtualenv_activate.sh
Run Code Online (Sandbox Code Playgroud)

...要么...

. virtualenv_activate.sh
Run Code Online (Sandbox Code Playgroud)

作为旁注,这就是为什么virtualenv总是说你需要使用"source"来运行它的激活脚本.  

  • 当你以我展示的方式运行这些脚本时,它实际上创建了一个NEW shell,并在该shell中运行脚本.由于"源"脚本的整个点是要更改当前的shell,这会破坏目的.使用"source virtualenv_activate.sh"或".virtualenv_activate.sh"运行脚本(注意第一个句点之后的空格). (5认同)

aru*_*mar 7

source是bash中的内置shell命令,在sh中不可用.如果我没记错,那么虚拟env会做很多路径和环境变量操作.即使运行它也bash virtualenv_blah.sh不会工作,因为这只会在子shell中创建环境.

尝试. virtualenv_activate.sh或者source virtualenv_activate.sh这基本上使脚本在当前环境中运行,并且virtualenv的activate修改的所有环境变量都可用.

HTH.

编辑:这是一个可能有用的链接 - http://ss64.com/bash/period.html


and*_*abs 5

在Mac OS X上,您的提案似乎无效.

我这样做了.我对解决方案不是很满意,但无论如何都要分享它并希望,也许有人会建议更好的解决方案:

activate.sh我有

echo 'source /Users/andi/.virtualenvs/data_science/bin/activate'
Run Code Online (Sandbox Code Playgroud)

我给出执行权限: chmod +x activate.sh

我这样执行:

`./activate.sh`
Run Code Online (Sandbox Code Playgroud)

请注意,有ASCII代码形式的paranthesis 96 =`(严重重音)