【问题标题】:Creating virtualenv in a Python script and running the rest in that env在 Python 脚本中创建 virtualenv 并在该 env 中运行其余部分
【发布时间】:2015-08-10 13:05:37
【问题描述】:

代码:

#!/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

基本上不用shell脚本来创建virtualenv,激活它,运行几个步骤我想用python脚本。

我错过了什么?这是正确的用例吗?

【问题讨论】:

  • 写一个shell脚本创建并激活virtualenv然后为你运行脚本不是更容易吗?

标签: python virtualenv


【解决方案1】:

我发现虚拟环境激活的东西都有点像脚本中的辛勤工作。在您的情况下,您是从 python 而不是 shell 执行此操作的,但我想这是相同的基本原理(之前没有见过 commands - 它们都在同一个子进程中运行)?

相反,我通常只使用 venv 中可执行文件的完整路径。这一切都更加明确,但话又说回来,这就是 python 方式:)

您必须注意的一件事是权限。

sudo -u whatever_user /path_to_myvenv/bin/pip install -r /some_path/requirements.txt

不确定这是否有帮助,但我希望直接调用 venv 中的二进制文件。

EDIT 刚刚玩了 commands - 他们每个人都是独立的(所以这可能是你问题的根本原因)

commands.getoutput('pwd')  # /somepath
commands.getoutput('cd /tmp')
commands.getoutput('pwd')  # still /somepath

我想做类似的事情:

commands.getoutput('virtualenv test')
commands.getoutput('test/bin/pip install wget')

【讨论】:

  • 所以当 os.system('/bin/bash --rcfile s.sh') 命令运行时 virtualenv 被激活但仍然打印语句显示 /usr/bin/python as python not /测试/bin/python ...任何想法
  • 请阅读另一个问题,os.system 调用将使 venv 保持激活状态。我不太了解那里发生了什么,但这对我来说有点像贝壳魔法。我会遵循获得更多选票的答案的建议。
  • 好吧,我也试过 subprocess,还有 cd 没有改变 dir >>> subprocess.call(['pwd']) /home/test 0 >>> subprocess.call(['cd ..'],shell=True) 0 >>> subprocess.call(['pwd']) /home/test 0
  • 您需要使用subprocess.call(['cd /tmp'], shell=True) - 但您会看到在下一次调用中目录实际上并没有改变。
  • 对吗?所以我有一个shell脚本来创建virtualenv,激活它,并在那个virtualenv中运行几个步骤,但是我们不能在python中做同样的事情吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-15
  • 1970-01-01
  • 1970-01-01
  • 2021-07-15
  • 2014-05-14
  • 1970-01-01
相关资源
最近更新 更多