Based on this link我在 Python 脚本中创建并激活了一个虚拟环境,但我想要的是在激活 virtualenv 之后,其余代码应该在 env 中运行,安装一些项目然后处理。
代码:
#!/usr/bin/python
import commands
import os
import time
import datetime
import sys
import json
import requests
out = commands.getoutput("wget <url>/s.sh")
new = commands.getoutput("chmod 755 s.sh")
env = "virtualenv " + "test"
#checking if env present if not create and activate it
try:
l=commands.getoutput('/bin/bash --rcfile s.sh')
except:
print env + " not present"
m = commands.getoutput(env)
print env + " not present so creating"
os.system('/bin/bash --rcfile s.sh')
v = commands.getoutput("which python")
print v + " python to be used"
v = commands.getoutput("pip install wget")
s.sh文件代码:-
#!/bin/sh
. test/bin/activate
基本上我想使用 python 脚本而不是 shell 脚本来创建 virtualenv、激活它并运行几个步骤。
我错过了什么?它是正确的用例吗?
请您参考如下方法:
我发现虚拟环境激活的东西有点太像脚本中的艰苦工作了。在你的情况下,你是从 python 而不是 shell 来做的,但我猜它是相同的基本原则(以前没有见过 commands - 它们都在同一个子进程中运行吗?
相反,我通常只使用 venv 中可执行文件的完整路径。这一切都更加明确,但话又说回来,这就是 python 方式:)
您必须注意的一件事是权限。
sudo -u whatever_user /path_to_myvenv/bin/pip install -r /some_path/requirements.txt
不确定这是否有帮助,但我希望直接调用 venv 中的二进制文件。
EDIT 刚刚玩过命令 - 它们中的每一个都是独立的(所以这可能是您问题的根本原因)
commands.getoutput('pwd') # /somepath
commands.getoutput('cd /tmp')
commands.getoutput('pwd') # still /somepath
我想做类似的事情:
commands.getoutput('virtualenv test')
commands.getoutput('test/bin/pip install wget')
