Search code examples
pythonpython-3.xfile-iononetypepsutil

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)

Solution

  • 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)