Skip to content Skip to sidebar Skip to footer

How To Inherit Stdin And Stdout In Python By Using Os.execv()

First, I wrote a c++ code as follows: #include int main() { int a,b; while(scanf('%d %d',&a,&b) == 2) printf('%d\n',a+b); return 0; } I

Solution 1:

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)

Post a Comment for "How To Inherit Stdin And Stdout In Python By Using Os.execv()"