使用fabric自动化virtualenv和Django开发服务器启动?

时间:2012-10-03 11:06:46

标签: django virtualenv fabric

  

可能重复:
  Activate a virtualenv via fabric as deploy user

我被建议尝试使用fabric将Django部署到生产服务器,并使用python而不是bash自动执行任务。

我想轻松启动并自动激活我的virtualenv,并在其中启动Django开发服务器。

我创建了一个名为fabfile.py的文件:

from fabric.api import local

def activate_env():
    local("source /.../expofit_env/bin/activate")

def run_local_server():
    local("/.../server/manage.py runserver")

def start():
    activate_env()
    run_local_server()

然而,当我跑

fab start

我收到以下消息:

[localhost] local: source /.../expofit_env/bin/activate
/bin/sh: 1: source: not found

Fatal error: local() encountered an error (return code 127) while executin
'source /.../expofit_env/bin/activate'

我做错了什么?


更新

根据Burhan Khalid的提议,我尝试了以下方法:

....
def activate_env():
    local("/bin/bash /.../expofit_env/bin/activate")
....

仅运行

fab activate_env

结果:

[localhost] local: /bin/bash /.../expofit_env/bin/activate

Done.

但执行后,virtualenv未激活。 对于以下代码:

def start_env(): 
    with prefix('/bin/bash /.../expofit_env/bin/activate'): 
        local("yolk -l")

我仍然收到错误,好像没有激活virtualenv。

alan@linux ~/Desktop/expofit $ fab start_env
[localhost] local: yolk -l
/bin/sh: 1: yolk: not found

当我手动激活virtualenv时,蛋黄工作正常:

alan@linux ~/.../expofit_env $ source bin/activate
(expofit_env)alan@linux ~/.../expofit_env $ yolk -l

DateUtils       - 0.5.2        - active 
Django          - 1.4.1        - active 
Python          - 2.7.3rc2     - active development (/usr/lib/python2.7/lib-dynload)
....

更新

尝试了this question的新方法。

from __future__ import with_statement
from fabric.api import *
from contextlib import contextmanager as _contextmanager

env.activate = 'source /.../expofit_env/bin/activate'

@_contextmanager
def virtualenv():
    with prefix(env.activate):
        yield

def deploy():
    with virtualenv():
        local('yolk -l')

给出了同样的错误:

[localhost] local: yolk -l
/bin/sh: 1: source: not found

Fatal error: local() encountered an error (return code 127) while executing 'yolk -l'

Aborting.

即使面团第一个命令也没有错误:

alan@linux ~/.../expofit_env/bin $ fab virtualenv

[servername] Executing task 'virtualenv'

Done.

更新

可以使用自定义shell运行local

from fabric.api import local

def start_env():
        local('source env/bin/activate',shell='/bin/bash')

然而,这并没有激活virtualenv,就好像它是手动完成的一样。

2 个答案:

答案 0 :(得分:3)

要使用fab文件中的virtualenv,您需要运行命令,如下所示:

def task():

    # do some things outside the env if needed 

    with prefix('source bin/activate'):
        # do some stuff inside the env
        pip install django-audiofield

with bloc中的所有命令都将在virtualenv

中执行

答案 1 :(得分:2)

默认情况下,您使用的是sh shell,而source命令是一种基础(即只能在bash中运行的东西)。

要激活您的环境,您需要直接使用bash执行它。 /bin/bash /path/to/bin/activate