开发者

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

开发者 https://www.devze.com 2022-12-21 01:16 出处:网络
In a bash script, I can write: exec 2>&1 exec someprog And the stderr output of someprog would be redirected to stdout.

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

精彩评论

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