[英]How to connect Paramiko stdin, stdout and stderr to console?
[英]MapReduce with paramiko how to print stdout as it streams
我使用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(),直到stdout.read停止。 因此,您必須分批讀取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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.