我正在尝试记录一个python脚本。当脚本如下时,记录时没有问题:-
print('Test')
但是,当我把它放在while循环中并休眠时,由于某种原因,它不会记录输出。
while(1):
print('Test')
time.sleep(3600)
我正在使用Ubuntu,我运行的日志命令是:-
python3 script.py > /home/usr/Test.txt
因此,当你像这样从bash写入文件时,在程序完成之前,你不会得到任何输出,所以让python从自己的代码中写入文件可能会更好。
这里有一个例子:
import time
while True:
new_data = 'hello fello!'
with open('file.txt', 'a+') as f:
f.write(new_data+'n')
time.sleep(2)
注意,我在新数据后添加了一个新行n
,以防止所有内容都在同一行上
open()
中的参数'a'
表示附加到文件,+
也表示读取。
您需要刷新流,以确保它立即被写入。
import time
import sys
while True:
print('Test')
sys.stdout.flush()
time.seep(3600)