如何从 python 中的 "with open() as f:" 之类的命令处理标准输出
How to handle stdout from command like "with open() as f:" in python
我正在尝试通过 ssh 传输大文件,目前可以很好地传输原始文件;如:
with open('somefile','r') as f:
tx.send(filepath='somefile',stream=f.read())
tx 是我拥有的更高级别的 class 实例,可以通过这种方式很好地传输,但我希望能够使用 pv
、dd
和tar
也可以直播。我需要的是:
with run_some_command('tar cfv - somefile') as f:
tx.send(filepath='somefile',stream=f.read())
这会将标准输出作为流写入远程文件。
我试过做类似的事情:
p = subprocess.Popen(['tar','cfv','-','somefile'], stdout=subprocess.PIPE)
tx.send(filepath='somefile',stream=p.stdout.readall())
但是没有用...
我一直在谷歌上搜索了一段时间,试图找到一个例子,但到目前为止还没有运气。
任何帮助将不胜感激!
我认为唯一的问题是 .readall()
方法不存在。
您可以使用p.stdout.read()
读取标准输出的全部内容:
p = subprocess.Popen(['tar','cfv','-','somefile'], stdout=subprocess.PIPE)
tx.send(filepath='somefile',stream=p.stdout.read())
我往回走,从一个基本的例子开始:
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))
成功了!感谢您的帮助。
我正在尝试通过 ssh 传输大文件,目前可以很好地传输原始文件;如:
with open('somefile','r') as f:
tx.send(filepath='somefile',stream=f.read())
tx 是我拥有的更高级别的 class 实例,可以通过这种方式很好地传输,但我希望能够使用 pv
、dd
和tar
也可以直播。我需要的是:
with run_some_command('tar cfv - somefile') as f:
tx.send(filepath='somefile',stream=f.read())
这会将标准输出作为流写入远程文件。 我试过做类似的事情:
p = subprocess.Popen(['tar','cfv','-','somefile'], stdout=subprocess.PIPE)
tx.send(filepath='somefile',stream=p.stdout.readall())
但是没有用... 我一直在谷歌上搜索了一段时间,试图找到一个例子,但到目前为止还没有运气。 任何帮助将不胜感激!
我认为唯一的问题是 .readall()
方法不存在。
您可以使用p.stdout.read()
读取标准输出的全部内容:
p = subprocess.Popen(['tar','cfv','-','somefile'], stdout=subprocess.PIPE)
tx.send(filepath='somefile',stream=p.stdout.read())
我往回走,从一个基本的例子开始:
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))
成功了!感谢您的帮助。