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

问题描述

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 中,我看不到任何“索引”信息。这是为什么?

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

我的跑步可能有什么问题?

解决方法

基于运行快速测试,我看到先打印到 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
$ 

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...