python入门操作HDFS

简述

在了解了Hadoop的基本使用后,需要通过编程语言进一步操作。对于没有Java基础的运维人,Python如何操作hdfs也就成了我们优先去学习的。

基础配置

#1.安装
mkvirtualenv -p python3.6 -a hadoop hadoop
pip install hdfs

#2.配置
vim ~/.hdfscli.cfg
#全局默认配置
[global]
default.alias = dev

#测试环境hadoop
[dev.alias]
url = http://dev.namenode:port
user = ann

#生产环境hadoop
[prod.alias]
url = http://prod.namenode:port
root = /jobs/

命令行界面

1.上传、下载文件

# 命令帮助
# hdfscli -h
Commands:
download
interactive
upload

#1. 下载文件
hdfscli download hadoop/input/anaconda-ks.cfg .
#2. 上传文件
hdfscli upload navicat121_mysql_cs_x64.tar.gz  /hadoop/input/
#3. 重定向到文件
hdfscli download hadoop/input/anaconda-ks.cfg - >> txt

2.交互模式

交互模式通过hdfs.client.Client进行实例化。

# hdfscli
Welcome to the interactive HDFS python shell.
The HDFS client is available as `CLIENT`.

>>> CLIENT.list('/hadoop/input')
['anaconda-ks.cfg', 'hadoop-2.7.2.tar.gz', 'navicat121_mysql_cs_x64.tar.gz']

>>> CLIENT.status('/hadoop/input/hadoop-2.7.2.tar.gz')
{
    
    'accessTime': 1604643646211, 'blockSize': 134217728, 'childrenNum': 0, 'fileId': 16389, 'group': 'supergroup', 'length': 212046774, 'modificationTime': 1603240571897, 'owner': 'root', 'pathSuffix': '', 'permission': '644', 'replication': 3, 'storagePolicy': 0, 'type': 'FILE'}

>>> CLIENT.delete('/hadoop/input/anaconda-ks.cfg')
True

python绑定

1.实例化

# 连接NameNode
from hdfs import InsecureClient
client = InsecureClient('http://10.10.10.56:50070', user='root')

# 读取开发环境的hadoop集群
from hdfs import Config
client = Config().get_client('dev')

2.读写文件

#1.读文件
# 判断路径是否存在
if not client.content('/hadoop/input/test.py', strict=False) is None:
    with client.read('/hadoop/input/test.py',encoding='utf-8', delimiter='\n') as reader:
        for line in reader:
            print(line)

#2.写文件
import json
data = {
    
    
    'name': 'jack',
    'age': 20
}
json_to_str = json.dumps(data)
client.write('/hadoop/input/data.json', data=json_to_str, encoding='utf-8') 

对于hdfs中路径不存在,会抛出一个HdfsError的异常,但是可以通过status()和content()自带参数strict=False来判断路径是否存在:

#/hadoop/in/test.py路径不存在
print(client.content('/hadoop/in/test.py', strict=False))
#打印输出结果
None

3.上传下载文件

#1.上传文件
client.upload('/hadoop/input', './test.py')
#2.下载文件
client.download('/hadoop/input/data.json', './data.json')

4.路径扩展

resolve()提供路径扩展功能,并允许使用特殊标记来标识路径。 例如,它当前支持#LATEST标记,该标记可扩展到给定文件夹内的最后修改文件。

#1.输出绝对路径,根据参数自动补全绝对路径,但此路径不会检查是否存在
print(client.resolve('hadoop/input'))
print(client.resolve('input'))
#打印输出结果
/hadoop/input
/input

#2.#LATEST标记,定位文件内最后修改的文件
print(client.resolve('hadoop/input/#LATEST'))
#打印输出结果
/hadoop/input/data1.json

#3.实例,data1.json为新增文件
print(client.resolve('hadoop/input/#LATEST'))
with client.read('hadoop/input/#LATEST') as reader:
    
    data = reader.read()
    print(data)
#打印输出结果
/hadoop/input/data1.json
b'{"name": "Sam", "age": 20}'

猜你喜欢

转载自blog.csdn.net/yanggd1987/article/details/109530725