如何设置Fabric任务的工作目录?

时间:2022-05-04 15:22:33

Assuming I define a trivial task to list files on a remote server:

假设我定义了一个简单的任务来列出远程服务器上的文件:

from fabric.api import run, env

env.use_ssh_config = True

def list_files():
    run('ls')

And I execute it with:

我执行它:

fab -H server list_files

How can I specify the working directory for the command I'm running, other than doing:

如何为我正在运行的命令指定工作目录,而不是:

run('cd /tmp && ls')

Which doesn't look very idiomatic to me?

哪个对我来说不是很惯用?

Disclaimer: I'm looking at Fabric for the first time in my life and I'm totally new to Python.

免责声明:我在生活中第一次看到Fabric,而且我对Python完全不熟悉。

1 个解决方案

#1


42  

Use the Context Manager cd:

使用Context Manager cd:

from fabric.api import run, env
from fabric.context_managers import cd

env.use_ssh_config = True

def list_files():
    with cd('/tmp'):
        run('ls')

#1


42  

Use the Context Manager cd:

使用Context Manager cd:

from fabric.api import run, env
from fabric.context_managers import cd

env.use_ssh_config = True

def list_files():
    with cd('/tmp'):
        run('ls')