Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按子流程模块捕获子流程的子流程的输出_Python - Fatal编程技术网

Python 按子流程模块捕获子流程的子流程的输出

Python 按子流程模块捕获子流程的子流程的输出,python,Python,我用Popen.communicate测试学生的程序。我发现了一个恼人的事实,这个API可能无法捕获子进程的子进程的输出 例如,一个学生写了一些这样的代码 if ((pid = fork()) == 0) { pwd(cwd); exit(0); } else { int ReturnCode; while (pid != wait(&ReturnCode)) {

我用Popen.communicate测试学生的程序。我发现了一个恼人的事实,这个API可能无法捕获子进程的子进程的输出

例如,一个学生写了一些这样的代码

    if ((pid = fork()) == 0)
    {
        pwd(cwd);
        exit(0);
    }
    else
    {
        int ReturnCode;
        while (pid != wait(&ReturnCode))
        {
            ;
        }
    }
pwd只打印当前目录

void pwd(const char *cwd)
{
    //printf("Current working directory is:\n");
    printf("%s\n", cwd);
}
我的测试脚本无法通过使用Popen.communicate获得任何输出。因为不使用多进程的程序可以通过我的测试脚本。我想问题的唯一原因是Popen.communication一些无法获取子进程的子进程的输出的信息

这里有没有步行的地方

编辑:

这是我的测试脚本

cd_command = '''cd /etc
pwd
cd /var
pwd
'''
def test_cd_pwd(self):
    # self.sh is the process that we are testing.
    self.out, self.err = self.sh.communicate(self.cd_command)
    self.assert_(self.out = "/etc\n/var\n")

我不能在这里复制这个;以下几点对我很有用:

c:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    int pid;
    if ((pid = fork()) == 0)
    {
        printf("Hello from child.\n");
        exit(0);
    }
    else
    {
        int ReturnCode;
        while (pid != wait(&ReturnCode))
        {
            ;
        }
        printf("Goodbye from parent.\n");
    }
}
/test.py的输出:

我还尝试:

打印时不使用换行符 使用shell运行Popen=True
在所有情况下,out都包含两个进程的输出。

您可能也希望粘贴测试过的python。
#!/usr/bin/python

from subprocess import Popen, PIPE

proc = Popen(['./a.out'], stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
print "out:", out
print "err:", err
out: Hello from child.
Goodbye from parent.

err: