2016-11-22 169 views
2

因此,我一直在Python中使用结构包来运行各种HDFS任务的shell脚本。检查一个文件是否存在于Python中的HDFS中

但是,无论何时我运行任务以检查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/': No such file or directory

Fatal error: local() encountered an error (return code 1) while executing 'hadoop fs -stat hdfs://some/nonexistent/hdfs/dir/'

Aborting.

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

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

回答

1

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

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 
相关问题