python程序输出无内容问题

您所在的位置:网站首页 python运行不报错又无任何结果输出错误怎么办 python程序输出无内容问题

python程序输出无内容问题

2024-07-17 14:36| 来源: 网络整理| 查看: 265

问题缘由

某项目中使用python脚本方式将日志文件中的数据持续的转换格式输出到另一文件中以供其他日志分析应用使用。但是当后台运行采取重定向方式输出到某一文件时,发现并没有内容输出,命令如下:

python xxx.py > xxx.log &

测试发现,当前台直接输出到终端时正常,使用后台运行重定向的方式输出到文件中时无法输出。

解决办法

发现是在程序运行时,输出有缓存,只有当程序运行结束或者缓冲区满后才会输出。因为程序是一致在运行的所以不可能等待程序结束在输出。并且要求是有实时性的所以等缓冲区满输出的方式也不可取。 所以采用在python运行时加上-u参数,如:

python -u xxx.py > xxx.log &

-u参数的意义是不使用缓冲的方式输入输出 详细如下:

Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. Note that there is internal buffering in xreadlines(), readlines() and file-object iterators (“for line in sys.stdin”) which is not influenced by this option. To work around this, you will want to use “sys.stdin.readline()” inside a “while 1:” loop.

参考:后台运行python程序输出缓冲区问题



【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3