gpt4 book ai didi

python - 从 Python 检查 HDFS 中是否存在文件

转载 作者:可可西里 更新时间:2023-11-01 14:36:35 25 4
gpt4 key购买 nike

因此,我一直在使用 Python 中的 fabric 包为各种 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/': 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 生成一个 bool 变量来告诉我目录或文件是否存在于 hdfs 中?

最佳答案

您可以只检查从 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

关于python - 从 Python 检查 HDFS 中是否存在文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40751218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com