如何使用Python监视HDFS中的目录以获取传入文件?(Python脚本由Docker Container执行;HDFS中没有Cronjob)

2024-05-16 22:51:47 发布

您现在位置:Python中文网/ 问答频道 /正文

场景:我的Python脚本正在部署在rancher(kubernetes集群)中的docker容器中运行。因此容器总是在运行。我想实现一个方法,在我的HDFS中监视一个目录以获取传入的文件。如果有新的文件,我希望脚本执行进一步的操作(预处理步骤来整理数据)。处理完新文件后,应将其删除。之后,脚本也在等待新的传入文件来处理它们。 因此,它不应该是HDFS中的cronjob。我需要在脚本中的代码,这是由docker容器执行的。目前我正在使用hdfs cli连接到hdfs。但我需要用python来做。在

有没有人知道Python库或者其他的方法来实现它?在


Tags: 文件方法docker目录脚本部署场景步骤
1条回答
网友
1楼 · 发布于 2024-05-16 22:51:47
#Schedule below script in crontab for interval of 1 min or 5 min based on your requirement
#Update the parameters(HDFSLocation,FileName,etc) as per the requirement
#Update the script to trigger alert(send mail/trigger another script if newHDFSFileCount > #previousHDFSFileCount)

import subprocess
import os

#Parameters
cwd=os.getcwd()
file='HDFSFileCount.txt'
fileWithPath=cwd+"/"+file
HDFSLocation="/tmp"
previousHDFSFileCount=0
newHDFSFileCount=0
#Calculate New HDFS file count
out = subprocess.Popen(['hadoop','fs','-ls', '/tmp/'], stdout=subprocess.PIPE).communicate()
if out[0][0]==0:
        newHDFSFileCount=0
else:
        newHDFSFileCount=out[0][6]

#
if os.path.exists(fileWithPath):
        f=open(fileWithPath,"r")
        previousHDFSFileCount=f.read()
else:
        f=open(fileWithPath,"w+")
        f.write(newHDFSFileCount)
        previousHDFSFileCount=newHDFSFileCount

f.close()

if (newHDFSFileCount>previousHDFSFileCount):
        f=open(fileWithPath,"w")
        f.write(newHDFSFileCount)
        #print(previousHDFSFileCount)
        #print(newHDFSFileCount)
        f.close()


相关问题 更多 >