python读取hadoop库数据_使用Python访问HDFS
最近接觸到大數(shù)據(jù),對(duì)于Skpark和Hadoop的料及都停留在第一次聽(tīng)到這個(gè)名詞時(shí)去搜一把看看大概介紹免得跟不上時(shí)代的層次。
在實(shí)際讀了點(diǎn)別人的代碼,又自己寫(xiě)了一些之后,雖然談不上理解加深,至少對(duì)于大數(shù)據(jù)技術(shù)的整體布局有了更清晰的認(rèn)識(shí)。
HDFS主要用來(lái)存儲(chǔ)文件系統(tǒng),雖然Spark有自己的RDD,但是似乎并未被啟用。我需要的數(shù)據(jù),是通過(guò)Spark服務(wù)啟動(dòng)的計(jì)算程序,寫(xiě)入HDFS中的。
#這結(jié)構(gòu)怎么看都感覺(jué)有點(diǎn)怪。
Spark支持Java、Scala和Python開(kāi)發(fā),對(duì)我來(lái)說(shuō)是個(gè)好事。唯一的問(wèn)題就是如何從HDFS中讀取我需要的數(shù)據(jù)。
Python的HDFS相關(guān)包有很多,我使用的是hdfs,根據(jù)官方文檔的說(shuō)法,同時(shí)支持hdfs和WebHDFS,默認(rèn)創(chuàng)建client的方式好像是WebHDFS,
需要通過(guò)datanode進(jìn)行文件操作,而HDFS則是通過(guò)namenode進(jìn)行文件操作,在這里卡了很久,也換過(guò)snakebite等包,直到把端口換成datanode,才正常連接。
※參照文檔:http://fatkun.com/2014/11/httpfs-and-webhdfs.html
hdfs包的安裝命令:
sudo pip install hdfs
啟動(dòng)hdfs:
>>> from hdfs.client import Client
>>> client = Client("http://localhost:50070") ?# 50070: Hadoop默認(rèn)namenode
>>> dir(client)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__registry__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_append', '_append_1', '_create', '_create_1', '_delete', '_get_content_summary', '_get_file_checksum', '_get_file_status', '_get_home_directory', '_list_status', '_mkdirs', '_open', '_rename', '_request', '_session', '_set_owner', '_set_permission', '_set_replication', '_set_times', '_timeout', 'checksum', 'content', 'delete', 'download', 'from_options', 'list', 'makedirs', 'parts', 'read', 'rename', 'resolve', 'root', 'set_owner', 'set_permission', 'set_replication', 'set_times', 'status', 'upload', 'url', 'walk', 'write']
>>>
其中用到的方法有:
walk() 類(lèi)似os.walk,返回值也是包含(路徑,目錄名,文件名)元素的數(shù)組,每層迭代。
read() 類(lèi)似file.read,官方文檔的說(shuō)法是client.read必須在with塊里使用:
with client.read(filepath) as fs:
content = fs.read()
write() 寫(xiě)文件,同樣需要在with塊中使用:
client.write(filepath, data=data_str, encoding='utf-8')
還有一種寫(xiě)法:
from hdfs.hfile import Hfile
hfile = Hfile(hostname, port, path, mode='w')
hfile.write(data)
hfile.close()
hfile = Hfile(hostname, port, path)
data = hfile.read()
hfile.close()
在filepath中,如果有不存在的路徑,會(huì)被直接創(chuàng)建出來(lái)。
目前用到的只有這些,后面如果涉及新的方法或者模塊,會(huì)繼續(xù)增加。
※ 關(guān)于Spark部署任務(wù)
Spark部署任務(wù)的命令,是spark-submit,語(yǔ)法是
./bin/spark-submit \
--class
--master \
--deploy-mode \
--conf = \
... # other options
\
[application-arguments]
默認(rèn)可以直接使用Java程序的jar包,Scala是基于Java的,同樣可以打包成jar,對(duì)于python文件,需要在處使用--py-files定義,單個(gè)文件可以直接寫(xiě)出,多個(gè)文件的話(huà)可以打包成.zip或.egg。
參考:http://spark.apache.org/docs/latest/submitting-applications.html
總結(jié)
以上是生活随笔為你收集整理的python读取hadoop库数据_使用Python访问HDFS的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: php的常量和变量的区别,php中常量与
- 下一篇: python standardscale