在Linux上,我使用supbprocess.Popen来运行一个应用程序.该应用程序的命令行需要输入文件的路径.我了解到我可以将路径/ dev / stdin传递给命令行,然后使用Python的subproc.stdin.write()将输入发送到子进程.
import subprocess
kw['shell'] = False
kw['executable'] = '/path/to/myapp'
kw['stdin'] = subprocess.PIPE
kw['stdout'] = subprocess.PIPE
kw['stderr'] = subprocess.PIPE
subproc = subprocess.Popen(['','-i','/dev/stdin'],**kw)
inbuff = [u'my lines',u'of text',u'to process',u'go here']
outbuff = []
conditionbuff = []
def processdata(inbuff,outbuff,conditionbuff):
for i,line in enumerate(inbuff):
subproc.stdin.write('%s\n'%(line.encode('utf-8').strip()))
line = subproc.stdout.readline().strip().decode('utf-8')
if 'condition' in line:
conditionbuff.append(line)
else:
outbuff.append(line)
processdata(inbuff,outbuff,conditionbuff)
这个应用程序还有一个MS Windows版本.在MS Windows上是否有使用/ dev / stdin的等价物,或者是Linux(Posix)特定的解决方案?
解决方法:
如果myapp处理 – 作为表示stdin的特殊文件名,则:
from subprocess import PIPE, Popen
p = Popen(['/path/to/myapp', '-i', '-'], stdin=PIPE, stdout=PIPE)
stdout, _ = p.communicate('\n'.join(inbuff).encode('utf-8'))
outbuff = stdout.decode('utf-8').splitlines()
如果你不能通过 – 那么你可以使用一个临时文件:
import os
import tempfile
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write('\n'.join(inbuff).encode('utf-8'))
p = Popen(['/path/to/myapp', '-i', f.name], stdout=PIPE)
outbuff, conditionbuff = [], []
for line in iter(p.stdout.readline, ''):
line = line.strip().decode('utf-8')
if 'condition' in line:
conditionbuff.append(line)
else:
outbuff.append(line)
p.stdout.close()
p.wait()
os.remove(f.name) #XXX add try/finally for proper cleanup
为了抑制stderr你可以将open(os.devnull,’wb’)作为stderr传递给Popen.