检查Python中的HDFS中是否存在文件

时间:2016-11-22 20:41:20

标签: python hadoop fabric

因此,我一直在使用Python中的结构包来运行各种HDFS任务的shell脚本。

但是,每当我运行任务来检查HDFS中是否已存在文件/目录时,它只会退出shell。这是一个例子(我使用的是Python 3.5.2和Fabric3 == 1.12.post1)

from fabric.api import local


local('hadoop fs -stat hdfs://some/nonexistent/hdfs/dir/')

如果目录不存在,则此代码生成

  

[localhost] local:hadoop fs -stat hdfs:// some / nonexistent / hdfs / dir /   stat:`hdfs:// some / nonexistent / hdfs / dir /':没有这样的文件或目录

     

致命错误:local()遇到错误(返回代码1)   执行' hadoop fs -stat hdfs:// some / nonexistent / hdfs / dir /'

     

中止。

我也试过了local('hadoop fs -test -e hdfs://some/nonexistent/hdfs/dir/'),但它引起了同样的问题。

如何使用fabric生成一个布尔变量,告诉我hdfs中是否存在目录或文件?

1 个答案:

答案 0 :(得分:1)

您只需检查从succeeded返回的结果对象的local标志即可。

from fabric.api import local
from fabric.context_managers import settings

file_exists = False
with settings(warn_only=True):
    result = local('hadoop fs -stat hdfs://some/nonexistent/hdfs/dir/', capture=True)
    file_exists = result.succeeded