How might I capture the output of my script w/out having to go to Linux (script.py > new_file.txt) ?
Asked
Active
Viewed 81 times
0
-
How about explain what platform you're on – MrJLP May 23 '17 at 17:50
1 Answers
1
Set stdout to the file you want to save:
import sys
sys.stdout = open('file', 'w')

L. Scott Johnson
- 4,213
- 2
- 17
- 28
-
Thanks! I can only see the output of direct print statements in my new file though. What I need it to do is capture the output to the screen on the fly as the program executes. – Cookies Monster May 23 '17 at 18:10
-
What else is producing output? Find out what those things are outputting to (stderr?) and capture that as well. – L. Scott Johnson May 23 '17 at 18:13
-
It's reaching to a database and grabbing back items as it does so. – Cookies Monster May 23 '17 at 18:23
-
If I do, script.py > new_file.txt...I can see it all. Yet, that's what I'm hoping to avoid. – Cookies Monster May 23 '17 at 18:27
-
Ah, then I assume your database library is the thing producing the output that isn't captured (not using python's sys handle, naturally). So yeah, there's not much you can do there unless you have access to that library's source and feel like getting your hands dirty. You'd have to switch it on the command line (the thing you want to avoid). Unless you want to cheat and fork a new shell process (see https://stackoverflow.com/questions/4760215/running-shell-command-from-python-and-capturing-the-output for that) – L. Scott Johnson May 23 '17 at 18:38
-
Something like this? subprocess.check_output(['ls', '-l']) It needs to write to a certain file name though. How might I enable that? – Cookies Monster May 23 '17 at 22:44
-
check_output, I believe, returns all of the stdout as a string. You could then write that returned string to the file of your choosing. (I haven't tested this) – L. Scott Johnson May 24 '17 at 00:35