我使用paramiko创建了一个小型Python脚本,该脚本允许我运行MapReduce作业,而无需使用PuTTY或cmd窗口来启动作业。这非常有效,只是在作业完成之前我无法看到stdout。我如何设置它,以便在生成stdout时可以看到它的每一行,就像我可以通过cmd窗口一样?
这是我的脚本:
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()
此代码隐式调用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