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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.