在本地主机上使用结构

use fabric on localhost

我想用 fabric 在我的本地机器上代替 shell 脚本来做一些事情。

例如,我想检查一个目录是否存在,如果它不创建那个目录。

我可以 运行 在本地使用 local('ls'),但我想使用 fabric 中的其他功能,例如 fabric.contrib.files.exists(path)

我已经尝试 RTFM 但缺少示例并没有帮助。

我如何 运行,例如,在我的本地主机上使用 fabric fabric.contrib.files.exists('/path/to/test')


以下是 ls 使用 local() 的方法:

from fabric.api import local
def test():
    local('ls')

这是一种笨拙的解决方案,需要我 ssh 到我的 localhost 才能完成任务:

from fabric.api import env
from fabric.contrib import files
env.hosts = ['127.0.0.1']
def test():
    if files.exists('/Users/ryan'):
        print 'path exists!'

所以我想要 local() 的易用性以及 fabric 附带的所有其他功能。

当谈到 fabric 缺少允许环回 ssh 连接时,您无法使用它们的辅助函数做很多事情。 local() (https://github.com/fabric/fabric/blob/1.11.1/fabric/operations.py#L1219) 只是 subprocess.. 的缩写,还有几行你通常需要写的代码,我不是说它没用,因为我已经在几次,但是 os 库可以做的远不止于此。

有一句老话,找对工作的工具。

exists() (https://github.com/fabric/fabric/blob/1.11.1/fabric/contrib/files.py#L18) 是 运行 tests -e <file path> 这将 return 0 表示一切正常,如果不存在则为 1。 -- 你是否已经看到这变得如此丑陋和失控,以至于当你 3 个月后回来看这个时你会更加困惑?!?!

如果你真的想用 local()local(test -e <file path>) ..我还是说只用 os.

-- ps,不要使用 local(ls) -- 好像没必要,subprocess 很贵,os 模块太快了,很好... os.listdir('.') 你为什么不看看光呢?! :P


老问题的回答

本地?在 os.path.isfile(<file>)os.path.isdir(<dir>) 中使用 os 由于 os 库维护得很好,因此 fabric 没有必要支持它。