简体   繁体   English

Bash 脚本激活(源)python virtualenv 使用 arguments

[英]Bash script to activate (source) python virtualenv using arguments

I have a python virtualenv folder in my home directory where i have quite a few python virtual environments, i would like to make a script that runs this command:我的主目录中有一个 python virtualenv 文件夹,其中有很多 python 虚拟环境,我想制作一个运行此命令的脚本:

$ source ~/Envs/env_that_i_specify_with_args/bin/activate.

Using an if else would work but i wanted something that looks in the ~/Envs/ directory so that when i add new envs i don't have to manually edit the script, but i could just use arguments to execute that command in another directory.(Something like $ activateEnv -1 , to run that command in the first folder in my ~/Envs/ directory, $ activateEnv -2 to run it in the second, etc.)使用 if else 可以,但我想要在~/Envs/目录中查找的内容,这样当我添加新环境时,我不必手动编辑脚本,但我可以使用 arguments 在另一个目录中执行该命令.(类似于$ activateEnv -1 ,在我的~/Envs/ directory, $ activateEnv -2在第二个文件夹中运行它,等等)

  • Any thoughts on how to do this?关于如何做到这一点的任何想法?
  • Please explain it in a rather simple manner as i am fairly new to Linux.请以相当简单的方式解释它,因为我对 Linux 相当陌生。

You cannot make a bash script doing this.您不能制作 bash 脚本来执行此操作。 The reason is rather simple.原因很简单。 A bash script is executed in a subprocess, the virtualenv would be changed for that subprocess, then the bash script ends, you go back to the parent process and restore exactly the same environment that you had before.在子进程中执行 bash 脚本,将为该子进程更改 virtualenv,然后 bash 脚本结束,您 go 恢复到父进程之前完全相同的环境。

In other words: A child process can never change the environment of a parent process.换句话说:子进程永远不能改变父进程的环境。

What you could do is:你可以做的是:

  • use a bash alias使用 bash 别名
  • use a shell function使用 shell function
  • create a script, but 'call' it with source <script_name>创建一个脚本,但使用source <script_name> '调用'它

You could for example add following lines to your ~/.bashrc or to your ~/.bash_aliases (if it is called by ~/.bashrc )例如,您可以将以下行添加到您的~/.bashrc或您的~/.bash_aliases (如果它被~/.bashrc调用)

setvenv() {
    source /path/to/your/venv_base_dir/$1/bin.activate
}

If you had for example following venvs例如,如果您有以下 venvs

/path/to/your/venv_base_dir/venvone
/path/to/your/venv_base_dir/venvtwo
/path/to/your/venv_base_dir/venvthree

Then you just had to type setvenv venvthree to activate.然后您只需键入setvenv venvthree即可激活。

You asked about activating the first, second or third venv whot would be the first one?你问过激活第一个、第二个或第三个 venv 谁会是第一个? the first in alphabetic order?第一个按字母顺序? The first one ordered by creation time?第一个按创建时间排序? I think using the name of the directory ( venvone , venvtwo , venvthree ) will probably be more intuitive especially if you give meaningful short name to your venvs.我认为使用目录的名称( venvonevenvtwovenvthree )可能会更直观,特别是如果你给你的 venvs 提供有意义的短名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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