Skip to main content
 首页 » 编程设计

python之在本地主机上使用结构

2024年10月24日10shanyou

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

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

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

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

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


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

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 lib 可以做的远不止于此。

有一句老话,找到适合工作的工具。

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

如果你真的想使用local()做 local(test -e <file path>) .. 我仍然说只使用 os .

-- ps,不要使用local(ls) -- 就像没有必要那样,subprocess很贵,os模块是如此之快,而且很好... os.listdir('.')为什么你不只是看到光?! :P


老问题的回答

本地?使用 os如 os.path.isfile(<file>)或 os.path.isdir(<dir>)自 os 以来,fabric 没有必要支持它lib 维护得很好。