Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么bash有时不将python程序的输出刷新到文件中_Bash_File_Flush - Fatal编程技术网

为什么bash有时不将python程序的输出刷新到文件中

为什么bash有时不将python程序的输出刷新到文件中,bash,file,flush,Bash,File,Flush,我有一个crontab作业,调用python脚本并输出到文件: python run.py &> current_date.log 现在有时候当我 tail -f current_date.log 我看到文件中充满了输出,但有时日志文件存在,但很长一段时间都是空的。我确信python脚本在开始运行并创建日志文件之后就开始打印东西了。你知道为什么它会有一段时间是空的吗?问题实际上是Python(不是bash)的问题,是设计的问题。默认情况下,Python缓冲输出。使用-u运行py

我有一个crontab作业,调用python脚本并输出到文件:

python run.py &> current_date.log
现在有时候当我

tail -f current_date.log

我看到文件中充满了输出,但有时日志文件存在,但很长一段时间都是空的。我确信python脚本在开始运行并创建日志文件之后就开始打印东西了。你知道为什么它会有一段时间是空的吗?

问题实际上是Python(不是bash)的问题,是设计的问题。默认情况下,Python缓冲输出。使用
-u
运行python以防止缓冲


另一个建议是创建一个类(或特殊函数),该类在写入日志文件后立即调用
flush()

Python在检测到未写入tty时缓冲输出,因此您的日志文件可能不会立即收到任何输出。您可以将脚本配置为刷新输出,也可以使用
-u
参数调用python以获得无缓冲输出

$ python -h

...

-u     : unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x)
         see man page for details on internal buffering relating to '-u'

...
重复问题: