Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I duplicate sys.stdout to a log file in python?
    primarykey
    data
    text
    <p>Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?</p> <p>My app has two modes. In interactive mode, I want all output to go to the screen as well as to a log file, including output from any system calls. In daemon mode, all output goes to the log. Daemon mode works great using <code>os.dup2()</code>. I can't find a way to "tee" all output to a log in interactive mode, without modifying each and every system call.</p> <hr> <p>In other words, I want the functionality of the command line 'tee' for any output generated by a python app, <strong>including system call output</strong>.</p> <p>To clarify: </p> <p>To redirect all output I do something like this, and it works great:</p> <pre><code># open our log file so = se = open("%s.log" % self.name, 'w', 0) # re-open stdout without buffering sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # redirect stdout and stderr to the log file opened above os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) </code></pre> <p>The nice thing about this is that it requires no special print calls from the rest of the code. The code also runs some shell commands, so it's nice not having to deal with each of their output individually as well.</p> <p>Simply, I want to do the same, except <em>duplicating</em> instead of redirecting.</p> <p>At first thought, I thought that simply reversing the <code>dup2</code>'s should work. Why doesn't it? Here's my test: </p> <pre><code>import os, sys ### my broken solution: so = se = open("a.log", 'w', 0) sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) os.dup2(sys.stdout.fileno(), so.fileno()) os.dup2(sys.stderr.fileno(), se.fileno()) ### print("foo bar") os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {}) os.execve("/bin/ls", ["/bin/ls"], os.environ) </code></pre> <p>The file "a.log" should be identical to what was displayed on the screen.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload