[英]Python redirect stdin/stdout with execv
I'm using python to os.fork
a child progress, and use os.execv
to execute another program in the child progress. 我使用python来
os.fork
子进度,并使用os.execv
在子进度中执行另一个程序。 How can I redirect I/O in the child program. 如何在子程序中重定向I / O。 I tried this but failed.
我试过了但是失败了。
import sys, os
pid = os.fork()
if pid is 0:
sys.stdin = open('./test.in')
os.execv('/usr/bin/python', ['python', './test.py'])
While test.py
is: 而
test.py
是:
import sys
print(sys.stdin)
a = input()
print(a)
After os.fork()
try this to redirect stdin and stderr: 在
os.fork()
尝试以下操作重定向stdin和stderr:
import os
STDIN_FILENO = 0
STDOUT_FILENO = 1
STDERR_FILENO = 2
# redirect stdout
new_stdout = os.open(stdout_file, os.O_WRONLY|os.O_CREAT|os.O_TRUNC)
os.dup2(new_stdout, STDOUT_FILENO)
# redirect stderr
new_stderr = os.open(stderr_file, os.O_WRONLY|os.O_CREAT|os.O_TRUNC)
os.dup2(new_stderr, STDERR_FILENO)
``` ```
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.