此Python代碼通過Perl腳本管理數據正常。如何使用Python將標準輸入/標準輸出傳遞給Perl腳本
import subprocess
kw = {}
kw['executable'] = None
kw['shell'] = True
kw['stdin'] = None
kw['stdout'] = subprocess.PIPE
kw['stderr'] = subprocess.PIPE
args = ' '.join(['/usr/bin/perl','-w','/path/script.perl','<','/path/mydata'])
subproc = subprocess.Popen(args,**kw)
for line in iter(subproc.stdout.readline, ''):
print line.rstrip().decode('UTF-8')
但是,它要求我首先將我的緩衝區保存到磁盤文件(/ path/mydata)。它是清潔器遍歷在Python代碼中的數據,並通過線由行到這樣的子過程:
import subprocess
kw = {}
kw['executable'] = '/usr/bin/perl'
kw['shell'] = False
kw['stderr'] = subprocess.PIPE
kw['stdin'] = subprocess.PIPE
kw['stdout'] = subprocess.PIPE
args = ['-w','/path/script.perl',]
subproc = subprocess.Popen(args,**kw)
f = codecs.open('/path/mydata','r','UTF-8')
for line in f:
subproc.stdin.write('%s\n'%(line.strip().encode('UTF-8')))
print line.strip() ### code hangs after printing this ###
for line in iter(subproc.stdout.readline, ''):
print line.rstrip().decode('UTF-8')
subproc.terminate()
f.close()
代碼發送所述第一線到子後使用readline掛起。我有其他可執行文件完全使用完全相同的代碼。
我的數據文件可能非常大(1.5 GB)有沒有辦法在不保存到文件的情況下管道化數據?我不想重寫perl腳本以與其他系統兼容。
謝謝。我用最終的代碼添加了一個答案 – tahoar 2012-01-02 13:57:11