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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With