【问题标题】:Reading / Writing Files from hdfs using python with subprocess, Pipe, Popen gives error使用带有子进程、管道、Popen 的 python 从 hdfs 读取/写入文件给出错误
【发布时间】:2015-01-25 17:40:53
【问题描述】:

我正在尝试在 python 脚本中的 hdfs 中读取(打开)和写入文件。但有错误。谁能告诉我这里出了什么问题。

代码(完整):sample.py

#!/usr/bin/python

from subprocess import Popen, PIPE

print "Before Loop"

cat = Popen(["hadoop", "fs", "-cat", "./sample.txt"],
            stdout=PIPE)

print "After Loop 1"
put = Popen(["hadoop", "fs", "-put", "-", "./modifiedfile.txt"],
            stdin=PIPE)

print "After Loop 2"
for line in cat.stdout:
    line += "Blah"
    print line
    print "Inside Loop"
    put.stdin.write(line)

cat.stdout.close()
cat.wait()
put.stdin.close()
put.wait()

当我执行时:

hadoop jar /usr/local/hadoop/share/hadoop/tools/lib/hadoop-streaming-2.5.1.jar -file ./sample.py -mapper './sample.py' -input sample.txt -output fileRead

它执行正确我找不到应该在 hdfs modifiedfile 中创建的文件

当我执行时:

 hadoop fs -getmerge ./fileRead/ file.txt

在 file.txt 中,我得到了:

Before Loop 
Before Loop 
After Loop 1    
After Loop 1    
After Loop 2    
After Loop 2

有人可以告诉我我在这里做错了什么吗?我不认为它是从 sample.txt 中读取的

【问题讨论】:

    标签: python hadoop hdfs popen hadoop-streaming


    【解决方案1】:

    尝试更改您的 put 子进程以通过更改它来自行获取 cat 标准输出

    put = Popen(["hadoop", "fs", "-put", "-", "./modifiedfile.txt"],
                stdin=PIPE)
    

    进入这个

    put = Popen(["hadoop", "fs", "-put", "-", "./modifiedfile.txt"],
                stdin=cat.stdout)
    

    完整脚本:

    #!/usr/bin/python
    
    from subprocess import Popen, PIPE
    
    print "Before Loop"
    
    cat = Popen(["hadoop", "fs", "-cat", "./sample.txt"],
                stdout=PIPE)
    
    print "After Loop 1"
    put = Popen(["hadoop", "fs", "-put", "-", "./modifiedfile.txt"],
                stdin=cat.stdout)
    put.communicate()
    

    【讨论】:

    • 您的答案在 hadoop fs -getmerge ./fileRead/file.txt 中的 sample.txt 中给了我相同的内容,而我在 hdfs 中找不到名为 modifiedfile.txt 的文件。我需要在 hdfs 中创建一个名为 modifiedfile 的文件吗?我认为这会在 hdfs 中创建一个名为 modifiedfile 的新文件。我错了吗?但是如果想在输出文件中写一些东西我该怎么办?
    • 远程hdfs如何连接?
    【解决方案2】:

    有人可以告诉我我在这里做错了什么吗??

    您的sample.py 可能不是合适的映射器。映射器可能会在标准输入上接受其输入并将结果写入其标准输出,例如blah.py:

    #!/usr/bin/env python
    import sys
    
    for line in sys.stdin: # print("Blah\n".join(sys.stdin) + "Blah\n")
        line += "Blah"
        print(line)
    

    用法:

    $ hadoop ... -file ./blah.py -mapper './blah.py' -input sample.txt -output fileRead
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      • 1970-01-01
      • 2011-05-05
      • 2018-03-11
      • 1970-01-01
      • 2011-01-22
      相关资源
      最近更新 更多