Python test()返回None。如何将其输出写入文件?
我正试图将Python test()返回None。如何将其输出写入文件?,python,python-3.x,file-io,nonetype,psutil,Python,Python 3.x,File Io,Nonetype,Psutil,我正试图将psutil.test()结果写入一个文件,但它会打印出文件中所需的文本,并将“无”写入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()
psutil.test()
结果写入一个文件,但它会打印出文件中所需的文本,并将“无”写入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()
不返回字符串。它打印一个字符串。一种解决方法是使用contextlib.redirect\u stdout
,这样字符串就会转到您的文件,而不是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)
请确保同时使用两个上下文管理器(带有语句的),否则您的文件将不会被刷新和关闭。文件和重定向使用单独的上下文管理器。psutil.test()
只打印到stdout
,但返回None
您可以使用将标准输出重定向到文件(例如,当使用打印时):
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()
正在向stdout
等生成输出,而不是打算将输出返回给用户。没有显式返回值的函数返回None
。检查文档中的函数,看看它是如何工作的。这会关闭文件吗?@aryamcarthy是的,在离开上下文管理器时,它会刷新并关闭文件:)我不太确定,因为open()
返回的文件句柄本身并没有被视为上下文管理器。另外,它应该用append模式'a'
打开。@aryamcarthy我很确定它会关闭文件,但你说得对,将其放入contextmanager并不难。它对文件和重定向使用单独的上下文管理器。