微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

你可以在Python的MS Windows上打开stdin作为文件吗?

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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐