这是 运行 在后台处理并将输出打印到 nohup 文件的正确方法吗?

Is this the right way to run process in background and print output into nohup file?

nohup python test.py &

在生成的nohup.out文件中,'print'输出没有写入其中,一些日志信息也没有写入nohup.out。这是正常的吗?我只想离开程序 运行 后台,我可以通过打开 nohup.out 定期检查程序的进度。例如,我的代码有这一行:

with open(file_name, 'r', encoding='utf8') :
    for index, line in enumerate(f):
        logger.info(index)
        #print(index)

通过打开nohup.out,我想看到'index'的当前值,这样我就知道它处理了多少内容。但是,在这个 nohup.out 中,我看不到任何 'index' 信息。这是为什么?

我以前用类似的方式运行编程,有时可以在nohup.out中看到索引。

我的 运行ning 可能出了什么问题?

基于 运行 快速测试,我看到首先打印到 stderr,然后在我的脚本末尾打印到 stdout。我怀疑您需要每隔一段时间显式刷新 stdout,或者您可以打印到 stderr。

要打印到 stderr,请定义此 eprint 函数并调用它而不是打印。

import sys
def eprint(*args,**kwrgs):
    print(*args,file=sys.stderr,**kwargs)

要刷新标准输出,请执行

import sys

sys.stdout.flush()#call this periodically

我的测试:

#test.py
import sys                                                                                                    
for x in range(0,10,2):                                      
    sys.stdout.write(str(x)+'\n')                          
    sys.stderr.write(str(x+1)+'\n')
nohup python test.py 
$ cat nohup.out
1
3
5
7
9
0
2
4
6
8
$