您可以在Python的MS Windows上将stdin作为文件打开吗? [英] Can you open stdin as a file on MS Windows in Python?

查看:42
本文介绍了您可以在Python的MS Windows上将stdin作为文件打开吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Linux上,我使用supbprocess.Popen运行应用程序.该应用程序的命令行需要输入文件的路径.我知道我可以将路径/dev/stdin传递到命令行,然后使用Python的subproc.stdin.write()将输入发送到子进程.

On Linux, I'm using supbprocess.Popen to run an app. The command line of that app requires a path to an input file. I learned I can pass the path /dev/stdin to the command line, and then use Python's subproc.stdin.write() to send input to the subprocess.

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)专用的解决方案?

There's also an MS Windows version of this app. Is there an equivalent on MS Windows to using the /dev/stdin or is the a Linux (Posix) specific solution?

推荐答案

如果 myapp -视为表示stdin的特殊文件名,则:

If myapp treats - as a special filename that denotes stdin then:

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()

如果您无法通过-,则可以使用一个临时文件:

If you can't pass - then you could use a temporary file:

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 .

To suppress stderr you could pass open(os.devnull, 'wb') as stderr to Popen.

这篇关于您可以在Python的MS Windows上将stdin作为文件打开吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆