我最近asked for explanations关于我无法理解的Fabric脚本行为。现在我了解了Fabric的工作原理,我仍然在努力寻找解决问题的方法: - )
基本上,我想要嵌套cd()
来电,prefix()
来电(可以从当前路径加载一些内容)和另一个cd()
来电最终run()
评论。
我想到的最好的例子如下:
with cd('/my/virtualenv/dir/'):
with prefix('source bin/activate'):
with cd('/my/project/dir/'):
run('pip install -r requirements.txt')
run('./run_something')
这不起作用,因为cd('/my/project/dir')
将优先于cd('/my/virtualenv/dir')
,这将从上下文中完全覆盖。
我能看到的唯一解决方案是连接一个唯一的prefix()
内的前3行,由&&
分隔,但它对我来说真的很像黑客:
with prefix('cd /my/virtualenv/dir/ && source bin/activate && cd /my/project/dir/'):
run('pip install -r requirements.txt')
run('./run_something')
还有其他/更优雅的方法吗?通过“更优雅”,我的意思是使用Fabric方法而不是我的黑客的解决方案。
当然,对于这个具体的例子,我可以使用virtualenvwrapper,但是它变得过于具体,并且不适用于不基于virtualenv的其他类似情况。
答案 0 :(得分:1)
我已经得到以下内容在我自己的机器上工作:
with cd("~/somedir"), prefix("source ~/.virtualenvs/venv/bin/activate"):
with cd("anotherdir"):
run("ls")
我真正的问题是,一旦你激活virtualenv,你为什么需要进入另一个目录?如果您只想使用pip
安装某些内容,这应该可以正常使用with cd('/my/virtualenv/dir/'), prefix('source bin/activate'):
run('pip install something')
我从fabric docs btw
获得with cd("dir"), prefix("stuff")
想法
修改强>:
作为我答案的更新:为什么不使用两条绝对路径?
with cd("/abs/path/to/my/file"), prefix("source /abs/path/to/my/venv/bin/activate"):
run("pip install something")
run("./somefile.py")
Fabric将执行类似于您尝试输入的命令:
Executed: /bin/bash -l -c "cd /abs/path/to/my/file && source ~/abs/path/to/my/venv/bin/activate && pip install something"
然后它会运行
./somefile.py