如何通过使用os.execv()在python中继承stdin和stdout [英] How to inherit stdin and stdout in python by using os.execv()

查看:100
本文介绍了如何通过使用os.execv()在python中继承stdin和stdout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我编写了如下的c ++代码:

First, I wrote a c++ code as follows:

#include <cstdio>
int main()
{
    int a,b;
    while(scanf("%d %d",&a,&b) == 2)
        printf("%d\n",a+b);
    return 0;
}

我用g++ -o a a.cpp进行编译.

然后,我编写了如下的python代码:

Afterwards, I wrote python code as follows:

import os,sys
sys.stdin = open("./data.in","r")
sys.stdout = open("./data.out","w")
pid = os.fork()
if pid == 0:
    cmd = ["./a","./a"]
    os.execv(cmd[0],cmd)

但是,data.out文件不包含任何内容.也就是说,子进程没有从其父进程继承stdin和stdout.但是当我编写如下的c ++代码时:

However, the data.out file contains nothing. That is to say, the child process did not inherit stdin and stdout from his parent process. But when I wrote a c++ code as follows:

#include<unistd.h>
#include<cstdio>
int main()
{
    freopen("data.in","r",stdin);a
    freopen("data.out","w",stdout);
    int pid = fork();
    if(pid == 0)
    {
        char* cmd[]= {"./a","./a"};
        execv(cmd[0],cmd);
    }
    return 0;
}

我在data.out中得到了正确的答案,也就是说execv在c ++代码中起作用.

I got the right answer in the data.out, that is to say execv works in the c++ code.

那么,我应该怎么做才能让execv也可以在python中工作?我真的需要此功能才能工作,有人可以告诉我吗?非常感谢!

So, what I should do to let execv also works in python? I really need this function to work, could anybody can tell me? thanks a lot!

data.in包含以下内容:

1 1

推荐答案

在python代码中,您打开了新IO流,并设置了sys.stdinsys.stdout Python 名称以指向这些.它们将具有自己的文件描述符(最有可能是3和4).但是,标准文件描述符01将保持不变,并继续指向其原始位置.这些是当您exec进入C ++程序中的stdin和stdout时继承的描述符.

In your python code, you've opened new IO streams and set the sys.stdin and sys.stdout Python names to point to these. They will have their own file descriptors (most likely 3, and 4). However the standard file descriptors, 0, and 1 will remain unchanged, and continue to point at their original locations. These are the descriptors inherited when you exec into stdin and stdout in your C++ program.

在执行之前,您需要确保调整了实际的文件描述符.

You need to make sure that the actual file descriptors are adjusted before execing.

os.dup2(sys.stdin.fileno(), 0)
os.dup2(sys.stdout.fileno(), 1)

这篇关于如何通过使用os.execv()在python中继承stdin和stdout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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