Why the following python code does not print to file - python

from sys import stdout
stdout = open('file', 'w')
print 'test'
stdout.close()
does create the file, but it contains nothing.
I had to use
import sys
sys.stdout = open('file', 'w')
print 'test'
sys.stdout.close()
But wouldn't the from ... import... automatically make the name available? Why do I still have to use sys.stdout instead of stdout?

The problem is this: print is equivalent to sys.stdout.write().
So when you do from sys import stdout, the variable stdout won't be used by print.
But when you do
import sys
print 'test'
it actually writes to sys.stdout which is pointing to the file you opened.
Analysis
from sys import stdout
stdout = open('file', 'w')
print 'test' # calls sys.stdout.write('test'), which print to the terminal
stdout.close()
import sys
sys.stdout = open('file', 'w')
print 'test' # calls sys.stdout.write('test'), which print to the file
sys.stdout.close()
Conclusion
This works...
from sys import stdout
stdout = open('file', 'w')
stdout.write('test')
stdout.close()

Related

It says "ValueError: I/O operation on closed file" but i opened it

I want to get the console output in a .txt file.
This is what i have:
import sys
print('some text')
a='moretext.1'.split('.')
sys.stdout = open('output.txt', 'w')
print(a)
sys.stdout.close()
here it works but in my program don't.
Does someone know what it could be?
It says that that its on line 2 or something
And I already searched on Stackoverflow and in the internet but i cant find anything
Do not mess with sys.stdout, instead open the file and print to it like so:
print('some text')
a='moretext.1'.split('.')
with open('output.txt', 'w') as out:
print(a, file=out)
Multiple ways to do so
1--
python3 myprogram.py > output.txt
2--
import sys
print('some text')
a='moretext.1'.split('.')
output = open('output.txt', 'w')
print(a, file=output)
output.close()
3--
import sys
print('some text')
a='moretext.1'.split('.')
stdout = sys.stdout
sys.stdout = open('output.txt', 'w')
print(a)
sys.stdout.close()
sys.stdout = sys.__stdout__
4--
As #Timur Shtatland suggested you can use a with statement

psutil.test() returns None. How to write its output to a file?

I'm trying to write the psutil.test() result to a file but instead it prints out the text that I want in the file and writes "None" to the test.txt.
import psutil
from time import sleep
while True:
proccesses = psutil.test()
file = open("test.txt", "a")
file.write(str(proccesses))
file.write("\n" * 10)
file.close()
sleep(5)
psutil.test() just prints to stdout but returns None.
You could use contextlib.redirect_stdout to redirect the standard output (e.g. when using print) to a file:
import contextlib
import time
import psutil
while True:
with open("test.txt", 'a') as fout, contextlib.redirect_stdout(fout):
psutil.test()
print("\n" * 10)
time.sleep(5)
psutil.test() doesn't return a string. It prints a string. A workaround would be to use contextlib.redirect_stdout, so that string goes to your file instead of STDOUT.
import psutil
from contextlib import redirect_stdout
from time import sleep
with open("test.txt", "a") as file:
with redirect_stdout(file):
while True:
psutil.test() # Will print to file.
file.write("\n" * 10) # or print("\n" * 10)
sleep(5)
Be sure to use both context managers (the with statements), or your file won't be flushed and closed. The redirect_stdout documentation uses separate context managers for the file and the redirection.

windows python stdout and stderr to two different files

I would like to output the stdout and stderr to two different log files.
i have tried this code but it only outputs the error to error log , but output is not redirected to runtime.log file.
the code is being run on windows and mostly robocopy is done in the code.
saveerr = sys.stderr
fsock = open('error.log', 'a')
sys.stderr = fsock
saveout = sys.stdout
fsock1 = open('runtime.log', 'a')
sys.stdout = fsock1
the sys.stdout area is not working. please let me know any correction in this code.
here is my entire code
import sys
saveerr = sys.stderr
fsock = open('error.log', 'a')
sys.stderr = fsock
saveout = sys.stdout
fsock1 = open('runtime.log', 'a')
sys.stdout = fsock1
##For site AUCB-NET-01 from source folder AUDC-RSTOR-01 E:\Canberra
exit_code1 = subprocess.call('robocopy \\\\aucb-net-01\\d$ \\\\nasaudc01\\remote_site_sync\\aucb-net-01 /E /MIR /W:2 /R:1', shell=True)
print ("exitcoode1=", exit_code1)
thanks to everyone for reading my post.
As mentioned in my comment your code should divert your stdout to the file. To get robocopy's stdout to go there too just echo each line to your stdout as shown in this link
https://stackoverflow.com/a/28319191/6550457
from subprocess import Popen, PIPE
import sys
saveerr = sys.stderr
fsock = open('error.log', 'a')
sys.stderr = fsock
saveout = sys.stdout
fsock1 = open('runtime.log', 'a')
sys.stdout = fsock1
cmd = 'robocopy \\\\aucb-net-01\\d$ \\\\nasaudc01\\remote_site_sync\\aucb-net-01 /E /MIR /W:2 /R:1'
p = Popen(cmd, stdout=sys.stdout, stderror=sys.stderr, bufsize=1, universal_newlines=True)
exit_code1 = p.wait()
see #eryksuns comments about robo copy and it's exit codes. http://ss64.com/nt/robocopy-exit.html

Not all the output is redirected into file in Python

I am trying to redirect all the stdout to a file, out.txt. But first commands's output display's on the terminal and the rest is fed to the file. I am not sure whats wrong in the piece of code below.
import os
import sys
import subprocess
orig_stdout = sys.stdout
f = file('out.txt', 'w')
sys.stdout = f
os.system("date") #First command
cmd = ["ls", "-al"]
exe_cmd = subprocess.Popen(cmd, stdout=subprocess.PIPE)
output, err = exe_cmd.communicate()
print output #Second command
sys.stdout = orig_stdout
Assigning a file object to sys.stdout redirects python code that uses sys.stdout but doesn't redirect code that uses the underlying file descriptor.
os.system("date")
spawns a new process that uses the underlying file descriptor, so its not redirected.
exe_cmd = subprocess.Popen(cmd, stdout=subprocess.PIPE)
output, err = exe_cmd.communicate()
print output #Second command
spawns a new process with a pipe that is read by the parent process. print uses the parent sys.stdout so it is redirected.
A standard way to redirect is to hand the file object to one of the subprocess calls. The child writes directly to the file without parent interaction.
with open('out.txt', 'w') as f:
cmd = ["ls", "-al"]
subprocess.call(cmd, stdout=f)

Closing a file with stdout being written to it

Suppose I am writing stdout to a file, like this:
sys.stdout = open("file.txt", "w")
# print stuff here
Doing this doesn't work:
sys.stdout.close()
How can I close a file after writing stdout to it?
I took your question to mean: "How can I redirect sys.stdout to a file?"
import sys
# we need this to restore our sys.stdout later on
org_stdout = sys.stdout
# we open a file
f = open("test.txt", "w")
# we redirect standard out to the file
sys.stdout = f
# now everything that would normally go to stdout
# now will be written to "test.txt"
print "Hello world!\n"
# we have no output because our print statement is redirected to "test.txt"!
# now we redirect the original stdout to sys.stdout
# to make our program behave normal again
sys.stdout = org_stdout
# we close the file
f.close()
print "Now this prints to the screen again!"
# output "Now this prints to the screen again!"
# we check our file
with open("test.txt") as f:
print f.read()
# output: Hello World!
Is this an answer to your question?
You can also do this if you want to redirect all print() to a file, which is a fast way and also usefull by my opinion but it could have other effects. If I'm wrong please correct me.
import sys
stdoutold = sys.stdout
sys.stdout = fd = open('/path/to/file.txt','w')
# From here every print will be redirected to the file
sys.stdout = stdoutold
fd.close()
# From here every print will be redirected to console
You can do this:
import sys
class writer(object):
""" Writes to a file """
def __init__(self, file_name):
self.output_file = file_name
def write(self, something):
with open(self.output_file, "a") as f:
f.write(something)
if __name__ == "__main__":
stdout_to_file = writer("out.txt")
sys.stdout = stdout_to_file
print "noel rocks"
The file is only open when you write to it like this.

Categories