VirtualEnv 从 bash 脚本初始化
我正在尝试编写一个超级简单的 bash 脚本。基本上激活一个虚拟环境,然后更改到工作目录。这是我经常做的一项任务,并且只服从一个命令是有意义的。
基本上...
#!/bin/bash
source /usr/local/turbogears/pps_beta/bin/activate
cd /usr/local/turbogears/pps_beta/src
但是,当它运行时,它只是转储回外壳,而我仍然在运行脚本的目录中,并且环境未激活。
I am trying to write what should be a super simple bash script. Basically activate a virtual env and than change to the working directory. A task i do a lot and condesing to one command just made sense.
Basically ...
#!/bin/bash
source /usr/local/turbogears/pps_beta/bin/activate
cd /usr/local/turbogears/pps_beta/src
However when it runs it just dumps back to the shell and i am still in the directory i ran the script from and the environment isn't activated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您所需要做的就是使用 source 命令运行脚本。这是因为 cd 命令是运行它的 shell 的本地命令。当您直接运行脚本时,将执行一个新的 shell,该 shell 在到达脚本文件末尾时终止。通过使用 source 命令,您可以告诉 shell 直接执行脚本的指令。
All you need to do is to run your script with the source command. This is because the cd command is local to the shell that runs it. When you run a script directly, a new shell is executed which terminates when it reaches the script's end of file. By using the source command you tell the shell to directly execute the script's instructions.
cd
的值是当前脚本的本地值,当您脱离文件末尾时,该脚本结束。您尝试做的事情并不是“超级简单”,因为您想覆盖此行为。
查看 exec 以将当前进程替换为您选择的进程。
要将命令输入交互式 Bash,请查看
--rcfile
选项。The value of
cd
is local to the current script, which ends when you fall off the end of the file.What you are trying to do is not "super simple" because you want to override this behavior.
Look at
exec
for replacing the current process with the process of your choice.For feeding commands into an interactive Bash, look at the
--rcfile
option.我想您希望您的脚本是动态的,但是,作为在新系统上工作时的快速修复,我创建了一个别名。
您现在可以通过从 CLI 中的任何位置键入 py1 来访问您的项目和 virtualenv。
我知道这远非理想,违反了 DRY 和许多其他编程概念。这只是一种快速但肮脏的方法,可以让您的环境和项目快速访问,而无需设置变量。
I imagine you wish your script to be dynamic, however, as a quick fix when working on a new system I create an alias.
You can now access your project and virtualenv by typing py1 from anywhere in the CLI.
I know that this is no where near ideal, violates DRY, and many other programming concepts. It is just a quick and dirty way of getting your env and project accessible quickly without having to setup the variables.
我知道我已经迟到了,但我可以建议使用 virtualenvwrapper 吗?它提供了一个很好的 bash 钩子,看起来完全可以做你想要的事情。
查看本教程: http:// blog.fruiapps.com/2012/06/Python-virtualenv-and-virtualenvwrapper 入门教程
I know that I'm late to the game here, but may I suggest using virtualenvwrapper? It provides a nice bash hook that appears to do exactly what you want.
Check out this tutorial: http://blog.fruiapps.com/2012/06/An-introductory-tutorial-to-python-virtualenv-and-virtualenvwrapper