开发者

Redirect stderr to stdout on exec-ed process from python?

In a bash script, I can write:

exec 2>&1
exec someprog

And the stderr output of someprog would be redirected to stdout.

Is there any开发者_C百科 way to do a similar thing using python's os.exec* functions?

This doesn't have to be portable, just work on Linux.


os.dup2(1, 2)

Illuminating examples

Let's execute /bin/ls with a bogus argument so that it complains to stderr.

$ python -c "import os; os.execl('/bin/ls', '', 'ffweew')" 1>/dev/null
: ffweew: No such file or directory
$ python -c "import os; os.execl('/bin/ls', '', 'ffweew')" 2>/dev/null
$ python -c "import os; os.dup2(1, 2); os.execl('/bin/ls', '', 'ffweew')" 1>/dev/null
$ python -c "import os; os.dup2(1, 2); os.execl('/bin/ls', '', 'ffweew')" 2>/dev/null
: ffweew: No such file or directory
$ 

First two invocations prove that ls does not write to stdout, and writes the error message to stderr.

In the 3rd and the 4th invocation, the Python program duplicates file descriptor 1 as file descriptor 2, achieving the desired effect.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜