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'