简体   繁体   中英

VirtualEnv initilaized from a bash script

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.

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.

I imagine you wish your script to be dynamic, however, as a quick fix when working on a new system I create an alias.

begin ie

the env is called 'py1' located at ~/envs/py1/ with a repository location at ~/proj/py1/

alias py1='source ~/envs/py1/bin/activate; cd ~/proj/py1/;

end ie

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM