简体   繁体   English

在 Fabric 中使用环境变量

[英]Using environment variables in Fabric

Assuming:假设:

export TEST=/somewhere

I want to run the command /somewhere/program using:我想使用以下命令运行命令/somewhere/program

with cd('$TEST'):
  run('program')

However, this doesn't work because the $ gets escaped.但是,这不起作用,因为$被转义了。

Is there a way to use an environment variable in a Fabric cd() call?有没有办法在 Fabric cd()调用中使用环境变量?

Following suggestion from @AndrewWalker, here is a more compact solution that worked for me (and to my knowledge, the result is the same):按照@AndrewWalker 的建议,这里有一个更紧凑的解决方案,对我有用(据我所知,结果是一样的):

with cd(run("echo $TEST")):
  run("program")

But I decided to go for a (very slightly) more concise yet as readable solution:但我决定采用(非常轻微)更简洁但可读的解决方案:

run('cd $TEST && program')

This second solution, if I am correct, produces the same result.如果我是正确的,第二个解决方案会产生相同的结果。

You can capture the value by using echo您可以使用 echo 捕获该值

testdir = str(run("echo $TEST"))
with cd(testdir):
    run("program")

Alternatively:或者:

import os

def my_task():
    with lcd(os.environ['TEST_PATH']):
        local('pwd')

os.getenv('TEST_PATH') may also be used (with a default, optionally) os.getenv('TEST_PATH')也可以使用(默认情况下,可选)

Hat tip: Send bash environment variable back to python fabric帽子提示: 将 bash 环境变量发送回 python fabric

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

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