如何使用 Fabric2.x 检查路径是否存在
How to check If Path Exists Using Fabric2.x
我正在使用 Fabric2 版本,但我没有看到它有 exist 方法来检查远程服务器中是否存在文件夹路径。请告诉我如何在 Fabric 2 中实现此目的 http://docs.fabfile.org/en/stable/。
我看过类似的问题,但这是针对 fabric 1.x 版本
您好,这并不难,您必须使用传统的 python 代码来检查路径是否已经存在。
from pathlib import Path
from fabric import Connection as connection, task
import os
@task
def deploy(ctx):
parent_deploy_dir = '/var/www'
deploy_dir ='/var/www/my_folder'
host = 'REMOTE_HOST'
user = 'USER'
with connection(host=host, user=user) as c:
with c.cd(parent_deploy_dir):
if not os.path.isdir(Path(deploy_dir)):
c.run('mkdir -p ' + deploy_dir)
你可以通过-d选项远程执行test命令来测试文件是否存在并且是一个目录同时将warn参数传递给运行方法因此在非零退出状态代码的情况下执行不会停止。如果文件夹不存在,则结果中的失败值将为 True,否则为 False。
folder = '/path/to/folder'
if c.run('test -d {}'.format(folder), warn=True).failed:
# Folder doesn't exist
c.run('mkdir {}'.format(folder))
exists
方法从 fabric.contrib.files
移动到 patchwork.files
并有一个小的签名更改,所以你可以像这样使用它:
from fabric2 import Connection
from patchwork.files import exists
conn = Connection('host')
if exists(conn, SOME_REMOTE_DIR):
do_something()
下面的代码是检查文件(-f)是否存在,改成'-d'即可目录的存在。
from fabric import Connection
c = Connection(host="host")
if c.run('test -f /opt/mydata/myfile', warn=True).failed:
do.thing()
您可以在下面的 Fabric 2 文档中找到它:
https://docs.fabfile.org/en/2.5/getting-started.html?highlight=failed#bringing-it-all-together
我正在使用 Fabric2 版本,但我没有看到它有 exist 方法来检查远程服务器中是否存在文件夹路径。请告诉我如何在 Fabric 2 中实现此目的 http://docs.fabfile.org/en/stable/。
我看过类似的问题
您好,这并不难,您必须使用传统的 python 代码来检查路径是否已经存在。
from pathlib import Path
from fabric import Connection as connection, task
import os
@task
def deploy(ctx):
parent_deploy_dir = '/var/www'
deploy_dir ='/var/www/my_folder'
host = 'REMOTE_HOST'
user = 'USER'
with connection(host=host, user=user) as c:
with c.cd(parent_deploy_dir):
if not os.path.isdir(Path(deploy_dir)):
c.run('mkdir -p ' + deploy_dir)
你可以通过-d选项远程执行test命令来测试文件是否存在并且是一个目录同时将warn参数传递给运行方法因此在非零退出状态代码的情况下执行不会停止。如果文件夹不存在,则结果中的失败值将为 True,否则为 False。
folder = '/path/to/folder'
if c.run('test -d {}'.format(folder), warn=True).failed:
# Folder doesn't exist
c.run('mkdir {}'.format(folder))
exists
方法从 fabric.contrib.files
移动到 patchwork.files
并有一个小的签名更改,所以你可以像这样使用它:
from fabric2 import Connection
from patchwork.files import exists
conn = Connection('host')
if exists(conn, SOME_REMOTE_DIR):
do_something()
下面的代码是检查文件(-f)是否存在,改成'-d'即可目录的存在。
from fabric import Connection
c = Connection(host="host")
if c.run('test -f /opt/mydata/myfile', warn=True).failed:
do.thing()
您可以在下面的 Fabric 2 文档中找到它:
https://docs.fabfile.org/en/2.5/getting-started.html?highlight=failed#bringing-it-all-together