2016-01-07 37 views
0

我已經創建了一個使用paramiko的小Python腳本,它允許我在不使用PuTTY或cmd窗口的情況下運行MapReduce作業來啓動作業。這很好,除非在作業完成之前我無法看到stdout。我怎麼能設置這個,以便我可以看到生成的每一行stdout,就像我可以通過cmd窗口一樣?MapReduce與paramiko如何打印標準輸出流

這裏是我的腳本:

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() 
+0

這似乎採取了一個適應例如由於緩衝來發生。不知何故,默認的行緩衝被覆蓋。你能說明你如何運行這個腳本和主機環境的細節嗎? – mohit

+0

我在Windows 7上的PyScripter IDE中運行此腳本。 –

回答

0

這段代碼是顯式地調用stdout.read()的阻塞,直到EOF。因此您必須以塊的形式讀取stdout/stderr才能立即獲得輸出。 this answer,尤其是this answer的修改版本應該可以幫助您解決此問題。我建議爲您的使用案例修改answer 2以防止出現一些常見的拖延情況。

這裏是從answer 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 
相關問題