python - 你能用 Python 在 MS Windows 上将标准输入作为文件打开吗?

标签 python windows linux 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- 视为表示标准输入的特殊文件名,则:

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.

关于python - 你能用 Python 在 MS Windows 上将标准输入作为文件打开吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8959601/

相关文章:

python - 我如何在 numpy 中向量化这个循环?

python - "Cannot deserialize instance of string from START_ARRAY value"Salesforce API问题

python - 关闭 subprocess.Popen 中的标准输入

windows - Ghostscript:ps2pdf 不适用于 Win 7 32 位

windows - 以管理员身份在 WiX 安装中运行 Powershell 脚本

linux - 更改默认目录结构

python - flask-sqlalchemy where in 子句查询语法是什么?

windows - Windows 7 上的 Python 3.4 中的 curses 需要什么?

linux - 在 OpenStack Swift 中禁用身份验证

linux - 每 30 秒进行一次日志轮换并将日志文件存储在以日期命名的目录中