Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 571
Lojas Avatar asked Nov 29 '25 16:11

Lojas


2 Answers

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)
like image 74
MSeifert Avatar answered Dec 02 '25 04:12

MSeifert


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.

like image 35
Arya McCarthy Avatar answered Dec 02 '25 06:12

Arya McCarthy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!