打印到文件 python 脚本作为后台进程运行

ell*_*len 6 python io background centos

我有一个需要大约 3 小时才能运行的 python 脚本。我想将它生成的一些数据打印到 .csv 文件中。

我在 centos 上,我正在像这样运行我的脚本:

python my_script.py > output.csv &
Run Code Online (Sandbox Code Playgroud)

我也试过:

python my_script.py &> output.csv 
Run Code Online (Sandbox Code Playgroud)

没有任何内容打印到 output.csv,甚至脚本开头的一些测试语句也没有。

我尝试的下一件事是在我的脚本中打开一个文件 -f = open('output.csv', 'a')并使用f.write(). 同样,文件中没有显示任何内容(尽管它确实被创建了)。

如何使用我想要的数据创建我的 output.csv?当它不是后台进程时,它似乎可以正常工作,但我希望它在后台运行。

我正在打印:

print('hello, this is a test')
Run Code Online (Sandbox Code Playgroud)

在另一个版本中,我有这样的事情:

f = open('output.csv', 'a')
f.write('hello, this is a test')
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,我得到的结果完全相同。文件被创建,但实际上没有写入任何内容。

任何帮助表示赞赏。谢谢!

cod*_*ody 5

尝试刷新标准输出缓冲区:

Python >= 3.3:

print('hello, this is a test', flush=True)
Run Code Online (Sandbox Code Playgroud)

早期版本:

import sys

print('hello, this is a test')
sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)