简体   繁体   English

从 python 脚本运行 virtualenvwrapper 命令

[英]Run virtualenvwrapper commands from python script

When I'm trying to create a new Python 3 virtual environment by using mkvirtualenv (virtualenvwrapper command) and os.system like this当我尝试使用mkvirtualenv (virtualenvwrapper 命令)和os.system创建一个新的 Python 3 虚拟环境时

import os
os.system('mkvirtualenv foo')

nothing happens.没发生什么事。

os.system("mate-terminal -e 'workon foo'")

doesn't work either.也不起作用。

The point is to quickly create a new virtual env and work on it later for each project (it's an automation script).重点是快速创建一个新的虚拟环境,并在以后为每个项目(它是一个自动化脚本)进行处理。 virtualenvwrapper is the most convenient option. virtualenvwrapper是最方便的选项。

The mkvirtualenv and workon commands are shell functions, not executables in your PATH [0]. mkvirtualenvworkon命令是 shell 函数,而不是PATH [0] 中的可执行文件。 To make them available in the shell you execute them in, you need to source the virtualenvwrapper.sh shell script defining them.要使它们在您执行它们的 shell 中可用,您需要获取定义它们的virtualenvwrapper.sh shell 脚本。 You might be better off calling virtualenv /path/to/foo directly.您最好直接调用virtualenv /path/to/foo

How to activate that virtualenv is another story, though, and will depend on the context you want to use it in. If you activate it in a subprocess, each process using it will have to be run in or under that child.然而,如何激活那个 virtualenv 是另一回事,这取决于你想要使用它的上下文。如果你在一个子进程中激活它,每个使用它的进程都必须在该子进程中或在该子进程下运行。

Hth, dtk hth, dtk

PS In addition, you might look into the subprocess module (or even the third-party sh ) for calling external programs. PS 此外,您可能会查看subprocess模块(甚至第三方sh )以调用外部程序。 Happy coding :)快乐编码:)

[0]: See $ which workon in a terminal vs $ which bash [0]:查看终端中的$ which workon$ which bash

The following codes in the bash shell script bash shell脚本中的以下代码

env_name="<your env name>"
echo "Create virtual environment"
source `which virtualenvwrapper.sh`
mkvirtualenv $env_name -p python<$version>
source $HOME/.virtualenvs/$env_name/bin/activate
workon $env_name

then run bash script (for example: test.sh ) from terminal source test.sh然后从终端source test.sh运行 bash 脚本(例如: test.sh

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

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