简体   繁体   English

如何写入Python子进程的stderr?

[英]How do I write to a Python subprocess' stderr?

This question is the same as python subprocess.Popen - write to stderr . 这个问题与python subprocess.Popen相同-写到stderr But there is no correct answers. 但是没有正确的答案。

I know this is correct. 我知道这是正确的。

import sys
sys.stderr.write('abcd')

Here is the code of subprocess(named input). 这是子进程(命名为input)的代码。 And I want the child process (input) to print the string written by parent process. 我希望子进程(输入)打印由父进程编写的字符串。

int main(int argc, char* argv[], char* envp[]){
    char buf[5];
    read(2, buf, 4);
    buf[4]=0;
    printf("%s\n", buf);
}

I want to write to a Python subprocess' stderr. 我想写一个Python子进程的stderr。 However, this is not correct. 但是,这是不正确的。 (Maybe you can correct this or just introduce me another way.) (也许您可以更正此问题,或者只是以其他方式介绍我。)

from subprocess import *
p = Popen(['./input'],stderr=PIPE)
p.stderr.write('abcd')

I got error like this. 我有这样的错误。

IOError: File not open for writing

Thanks for your help. 谢谢你的帮助。

os.pipe() os.pipe()

Open a pipe to or from command. 打开与命令之间的管道。 The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'. 返回值是连接到管道的打开文件对象,可以根据模式是“ r”(默认)还是“ w”来进行读取或写入。 The bufsize argument has the same meaning as the corresponding argument to the built-in open() function. bufsize自变量与内置open()函数的相应自变量具有相同的含义。 The exit status of the command (encoded in the format specified for wait()) is available as the return value of the close() method of the file object, except that when the exit status is zero (termination without errors), None is returned. 该命令的退出状态(以为wait()指定的格式编码)可用作文件对象的close()方法的返回值,但退出状态为零(无错误终止)时,则无回来。

Change your Python code to this: 将您的Python代码更改为此:

from subprocess import *
import os

r, w = os.pipe()
p = Popen(['./input'],stderr=r, stdout=PIPE)
os.close(r)
os.write(w, b'abcd')
os.close(w)
print(repr(p.communicate()[0]))

You can read Python os.pipe Examples . 您可以阅读Python os.pipe示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM