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

file-descriptor, linux, python, redirect

Solution

`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.

Problem

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 way to do a similar thing using python's `os.exec*` functions? This doesn't have to be portable, just work on Linux.

Original source