简体   繁体   English

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

[英]Printing to file python script running as a background process

I have a python script that takes about 3 hours to run. 我有一个python脚本,运行大约需要3个小时。 I want to print some of the data it generates to a .csv file. 我想将它生成的一些数据打印到.csv文件中。

I'm on centos and I'm running my script like so: 我正在使用centos,我正在运行我的脚本:

python my_script.py > output.csv &

I also tried: 我也尝试过:

python my_script.py &> output.csv 

Nothing prints to output.csv, not even some test statements right at the beginning of the script. 什么都没有打印到output.csv,甚至没有打印到脚本开头的一些测试语句。

The next thing I tried was opening a file in my script - f = open('output.csv', 'a') and writing to it using f.write() . 我尝试的下一件事是在我的脚本中打开一个文件 - f = open('output.csv', 'a')并使用f.write()写入它。 Again, nothing shows up in the file (although it does get created). 同样,文件中没有任何内容显示(虽然它确实被创建)。

How can I create my output.csv with the data that I want? 如何使用我想要的数据创建output.csv? It seems to work normally when it's not a background process but I'd like it to run in the background. 它似乎在不是后台进程时正常工作,但我希望它在后台运行。

I'm printing just like so: 我是这样打印的:

print('hello, this is a test')

and in another version, I have something like this: 而在另一个版本中,我有这样的事情:

f = open('output.csv', 'a')
f.write('hello, this is a test')

I get exactly the same result in both cases. 在这两种情况下,我得到完全相同的结果。 The file gets created, but nothing is actually written to it. 文件被创建,但实际上没有写入任何文件。

Any help is appreciated. 任何帮助表示赞赏。 Thank you! 谢谢!

Try flushing the stdout buffer: 尝试刷新stdout缓冲区:

Python >= 3.3: Python> = 3.3:

print('hello, this is a test', flush=True)

Earlier versions: 早期版本:

import sys

print('hello, this is a test')
sys.stdout.flush()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM