从 Python 检查 HDFS 中是否存在文件
Check if a file exists in HDFS from Python
所以,我一直在 Python 到 运行 shell 脚本中使用 fabric 包来执行各种 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 中?
您可以只检查从 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 到 运行 shell 脚本中使用 fabric 包来执行各种 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 中?
您可以只检查从 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