python subprocess.Popen - 写入标准错误 [英] python subprocess.Popen - write to stderr

查看:41
本文介绍了python subprocess.Popen - 写入标准错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从 stderr 读取的 c 程序(我不是作者).我使用 subprocess.Popen 调用它,如下所示.有没有办法写入子进程的stderr.

I have a c program (I'm not the author) that reads from stderr. I call it using subprocess.Popen as below. Is there any way to write to stderr of the subprocess.

proc = subprocess.Popen(['./std.bin'],stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

推荐答案

如果子进程从stderr读取(注意:通常stderr是打开输出的):

If the child process reads from stderr (note: normally stderr is opened for output):

#!/usr/bin/env python
"""Read from *stderr*, write to *stdout* reversed bytes."""
import os

os.write(1, os.read(2, 512)[::-1])

然后你可以提供一个伪 tty(这样所有的流都指向同一个地方),就像它是一个普通的子进程一样处理子进程:

then you could provide a pseudo-tty (so that all streams point to the same place), to work with the child as if it were a normal subprocess:

#!/usr/bin/env python
import sys
import pexpect # $ pip install pexpect

child = pexpect.spawnu(sys.executable, ['child.py'])
child.sendline('abc') # write to the child
child.expect(pexpect.EOF)
print(repr(child.before))
child.close()

输出

u'abc\r\n\r\ncba'

您也可以使用subprocess + pty.openpty()代替<代码>pexpect.

You could also use subprocess + pty.openpty() instead pexpect.

或者您可以编写特定于奇怪的 stderr 行为的代码:

Or you could write a code specific to the weird stderr behavior:

#!/usr/bin/env python
import os
import sys
from subprocess import Popen, PIPE

r, w = os.pipe()
p = Popen([sys.executable, 'child.py'], stderr=r, stdout=PIPE,
          universal_newlines=True)
os.close(r)
os.write(w, b'abc') # write to subprocess' stderr
os.close(w)
print(repr(p.communicate()[0]))

输出

'cba'

这篇关于python subprocess.Popen - 写入标准错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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