mapreduce和paramiko如何在流媒体时打印stdout

u4dcyp6a  于 2021-05-29  发布在  Hadoop
关注(0)|答案(1)|浏览(440)

我使用paramiko创建了一个小python脚本,它允许我运行mapreduce作业,而不使用putty或cmd窗口来启动作业。这很好用,只是在工作完成之前我不能看到stdout。我如何设置它,使我可以看到每一行的标准输出,因为它是生成的,就像我将能够通过命令窗口?
这是我的剧本:

import paramiko

# Define connection info

host_ip = 'xx.xx.xx.xx'
user = 'xxxxxxxxx'
pw = 'xxxxxxxxx'

# Commands

list_dir = "ls /nfs_home/appers/cnielsen -l"
MR = "hadoop jar /opt/cloudera/parcels/CDH/lib/hadoop-0.20-mapreduce/contrib/streaming/hadoop-streaming.jar -files /nfs_home/appers/cnielsen/product_lookups.xml -file /nfs_home/appers/cnielsen/Mapper.py -file /nfs_home/appers/cnielsen/Reducer.py -mapper '/usr/lib/python_2.7.3/bin/python Mapper.py test1' -file /nfs_home/appers/cnielsen/Process.py -reducer '/usr/lib/python_2.7.3/bin/python Reducer.py' -input /nfs_home/appers/extracts/*/*.xml -output /user/loc/output/cnielsen/test51"
getmerge = "hadoop fs -getmerge /user/loc/output/cnielsen/test51 /nfs_home/appers/cnielsen/test_010716_0.txt"

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host_ip, username=user, password=pw)

## stdin, stdout, stderr = client.exec_command(list_dir)

## stdin, stdout, stderr = client.exec_command(getmerge)

stdin, stdout, stderr = client.exec_command(MR)

print "Executing command..."

for line in stdout:
    print '... ' + line.strip('\n')
for l in stderr:
    print '... ' + l.strip('\n')
client.close()
9udxz4iz

9udxz4iz1#

这段代码隐式地调用stdout.read(),直到eof。因此,您必须分块读取stdout/stderr以立即获得输出。这个答案,尤其是这个答案的一个修改版本应该可以帮助你解决这个问题。我建议根据您的用例调整答案2,以防止一些常见的延迟场景。
下面是一个改编自答案1的例子

sin,sout,serr = ssh.exec_command("while true; do uptime; done")

def line_buffered(f):
    line_buf = ""
    while not f.channel.exit_status_ready():
        line_buf += f.read(1)
        if line_buf.endswith('\n'):
            yield line_buf
            line_buf = ''

for l in line_buffered(sout):   # or serr
    print l

相关问题