2016-08-01 15 views
1

我想通過ssh傳輸大文件,並且可以當前流式傳輸原始文件;如:如何從命令中處理標準輸出,例如「在open()中使用f:」python

with open('somefile','r') as f: 
    tx.send(filepath='somefile',stream=f.read()) 

TX是,我有可以流就好了這樣一個更高的水平類的實例,但我希望能夠使用命令,如pvddtar以流爲好。我需要的是:

with run_some_command('tar cfv - somefile') as f: 
    tx.send(filepath='somefile',stream=f.read()) 

這將採取stdout作爲流並寫入遠程文件。 我試着做這樣的事情:

p = subprocess.Popen(['tar','cfv','-','somefile'], stdout=subprocess.PIPE) 
tx.send(filepath='somefile',stream=p.stdout.readall()) 

但無濟於事...... 我一直在google搜索試圖找到一個例子一段時間,但至今沒有運氣。 任何幫助將不勝感激!

回答

0

我認爲唯一的問題是.readall()方法,即不存在。

您可以使用p.stdout.read()讀取標準輸出的全部內容:

p = subprocess.Popen(['tar','cfv','-','somefile'], stdout=subprocess.PIPE) 
tx.send(filepath='somefile',stream=p.stdout.read()) 
0

我走了回來,並開始與一個基本的例子:

calc_table_file = '/mnt/condor/proteinlab/1468300008.table' 

import subprocess 
class TarStream: 
    def open(self,filepath): 
    p = subprocess.Popen(['tar','cfv','-',filepath], stdout=subprocess.PIPE) 
    return(p.stdout) 


import paramiko 


def writer(stream): 
    ssh = paramiko.SSHClient() 
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
    ssh.connect('asu-bulk-uspacific', username='labtech', password=password) 
    client = ssh.open_sftp() 
    with client.open('/mnt/cold_storage/folding.table','w') as f: 
    while True: 
     data = stream.read(32) 
     if not data: 
     break 
     f.write(data) 

## works with normal 'open' 
with open(calc_table_file,'r') as f: 
    writer(f) 

## and popen :) 
tar = TarStream() 
writer(tar.open(calc_table_file)) 

和它的工作!謝謝您的幫助。

相關問題